BerkinAkkaya

Basic 2D Shooting System

Sep 29th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.87 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Weapon : MonoBehaviour {
  4.  
  5.     /* Berkin AKKAYA */
  6.     /* berkinakkaya.wixsite.com/blog */
  7.  
  8.     [Header("Weapon Specifications")]
  9.     [SerializeField] [Range(0.0f, 10.0f)] float fireRate;
  10.     [SerializeField] float bulletSpawnOffset;
  11.     [SerializeField] GameObject bulletPrefab;
  12.    
  13.     //Variables used for shooting system
  14.     bool allowFire = false;
  15.     float nextFire = 0;
  16.  
  17.     #region Update
  18.     void Update(){
  19.         Shoot();
  20.     }
  21.     #endregion
  22.  
  23.     #region Shooting
  24.     void CreateBullet(){
  25.         GameObject bullet = Instantiate(bulletPrefab);
  26.         bullet.transform.position = transform.position + transform.up * bulletSpawnOffset;
  27.     }
  28.  
  29.     void Shoot(){
  30.         nextFire -= fireRate * Time.deltaTime;
  31.  
  32.         if(allowFire && Input.GetMouseButton(0)){
  33.             CreateBullet();
  34.             allowFire = false;
  35.             return;
  36.         }
  37.  
  38.         if(nextFire <= 0){
  39.             allowFire = true;
  40.             nextFire = 1f;
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment