333GameStudio

shooting script with ammo

Mar 6th, 2015
1,036
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  var reloadSound : AudioClip;
  2.  
  3.  var sound : AudioClip;
  4.  
  5.  var BulletSpeed = 100; //force of bullets being shot
  6.  
  7.  var projectile : Rigidbody; //bullet prefab goes here
  8.  
  9.  var bullets = 30; //amount of bullets per "clip"
  10.  
  11.  var totalBullets = 60; //total amount of bullets we have available
  12.  
  13.  var reloadTime = 3; //time to reload
  14.  
  15.  var reloadAmount = 10;
  16.  
  17.  var ammo : GUIText; //GUI text for our bullet/ammo count
  18.  
  19.  var rate : float = 0.5;
  20.  
  21.  private var rate_time : float;
  22.  
  23.  function Update () {
  24.  
  25.  Fire ();
  26.  
  27.  Reload ();
  28.  
  29.  }
  30.  
  31.  function Fire () {
  32.  
  33.  if(bullets > 0) { //if we have at least 1 bullet then we can fire
  34.  
  35.  if (Input.GetButtonDown("Fire1") && Time.time > rate_time) {
  36.  
  37.   rate_time = Time.time + rate;
  38.  
  39.  var clone : Rigidbody;// Instantiate the projectile at the position and rotation of this transform
  40.  
  41.  clone = Instantiate(projectile, transform.position, transform.rotation);
  42.  
  43.  clone.velocity = transform.TransformDirection (Vector3.forward * BulletSpeed);// Give the cloned object an initial velocity along the current
  44.  
  45.  AudioSource.PlayClipAtPoint(sound, transform.position, 1);                     // object's Z axis
  46.  
  47.  bullets -=1; //subtracts one bullet per fire sequence
  48.  
  49.  }
  50.  
  51.  }
  52.  
  53.  }
  54.  
  55.  function Reload () {
  56.  
  57.  if(bullets < 1) {    //if we have less than 1 bullet then we can reload
  58.   if (totalBullets > 0)
  59.  
  60.  if(Input.GetKeyDown("r")) {
  61.  
  62.  AudioSource.PlayClipAtPoint(reloadSound, transform.position, 1); //plays reload soundclip
  63.  
  64.  yield WaitForSeconds(reloadTime); //waits for "reloadTime" before adding bullets
  65.  
  66.  bullets += reloadAmount; //adds 3 bullets to our "clip"
  67.  
  68.  totalBullets -= reloadAmount; //subtracts 3 bullets from our totalBullets amount
  69.  
  70.  }
  71.  
  72.  }
  73.  
  74.  }
  75.  
  76.  function OnGUI () {
  77.  
  78.  ammo.text = "bullets: " + bullets + "/" +  totalBullets.ToString();
  79.  
  80.  }
Advertisement
Add Comment
Please, Sign In to add comment