Fire Rate Code.

Hello all,

I have some code that allows for the player to shoot in two different ways based on the public variable set in the inspector - I could change the value through code, but, haven’t gotten around to it yet.

The code allows for shooting in a single shot method where you have to press the button to fire, and if a fireRate is set above 0, you can fire continuously with a pause between every shot for as long as needed. But, I would like to replace the second option with burst fire. Meaning, that if the user was to push: Input.GetButton(Keycode.Space) - this project uses the mouse - it would fire a number of projectiles (around 3-5 might be good), again, with a pause between each one, as I currently have, but, then have a period where there is no firing, a cool-down period if you will, before firing recommences or the button is released. But I can’t think of how to implement that.

The code I have is:

[code=CSharp]

// Update is called once per frame
    void Update () {
        //deal with weapons - single burst or multiple
        //outer if
        if (fireRate == 0)
        {
            //Shoot ();
            //inner if
            if(Input.GetButtonDown("Fire1"))
            {
                Shoot();
            } //end inner if
        }//end outer if for the else command
        else
        {
            //inner if in the else function also using &&
            if (Input.GetButton("Fire1") && Time.time > nextFire)
            {
                //this below is unity docs example
                nextFire = Time.time + fireRate;
                Shoot ();
                //print ("coolio");
            }
        }

    }//end Update()

The Shoot() function is basically your standard instantiate type thingy and have left it out for the sake of brevity.

If anyone can help with a solution then here is a big thankyou in advance!!! :sunglasses:.

Ok, I can help you, but I need to see what is in Shoot(), cause “Standard Instantiate” is not enough, for me at least to provide a perfectly porblem solving answer. However, I can give you a not so “perfectly problem solving” answer considering only the information you have given to me:

   float cooldownSeconds = [Whatever you want];
   float cooldown;
   int maxAmmo = [Whatever you want];
   int ammo;

    void Update () {
        if (fireRate == 0 && Input.GetButtonDown("Fire1"))
        {   //Reduced to a single if, cause It does exactly the same
            //And in my Opinion, looks better. (You might want not to
            //in case you have anything else here that do needs the if)
            Shoot ();
        }
        else
        {
            if (Input.GetButton("Fire1") && Time.time > nextFire && fireRate > 0)
            {
            //I added "&& fireRate > 0", because if not, this will run if the user decides
            //to hold the button, as "GetButtonDown" only returns true the frame the button
            //is pressed, and while its hold, is false, so the "else" will run, and so will this.
                if (ammo > 0)
                {   //If you have ammo
                   nextFire = Time.time + fireRate;
                   Shoot ();
                   ammo--; //Explained by itself
                }
                if (ammo == 0)
                {   //If you no longer have ammo
                   if (cooldown > Time.time)
                   {   //If there is no cooldown (relatively)
                      cooldown = Time.time + cooldownSeconds;
                   }
                }
            }
        }

       if (Time.time > cooldown && ammo == 0)
       {   //If the cooldown is over, and you have no ammo cause else this will run kinda always,
           //as here we set the ammo to maxAmmo, and cooldown only happens when you run out
           //of ammo, then you will be constantly fulling the ammo.
           ammo = maxAmmo;
       }

    } //End of Update()

If you want to fire “3-5 projectiles”, then you should replace “maxAmmo”, by “Random.Range(2, 6)”. (Or maybe Random.Range(3, 6), I know the second one is Inclusive, but dont remember the first one)

1 Like

Rightio, I’m just re-jigging the Shoot() Function right now make sure it works as advertised :p. I needed to make some alterations like make it work of a keyboard key rather than the mouse button and I decided to add a muzzle flash as the shot is fired and having a bit of a problem making it find the child object at the point of the flash - aaarrrgghhh!

I need to learn a lot more. I’ll post the code for shoot as soon as I can.

Ok, just got it working - for now - this is the Shoot() function. Pretty bare bones and not much going on. Now if it can be done better than this or if it’s done incorrectly it’s because I have no idea what I’m doing :smile:. The course I am doing is good, but, I like to add stuff to the standard fare and that’s where I run into problems many, many problems.

public void Shoot(){
     print ("We are in Shoot...");

     //play the sound???
     audio.PlayOneShot(laserShot, 1.0f);

     //GameObject go = Instantiate (bulletThingy, firePointPosition, Quaternion.identity) as GameObject;
     clone = Instantiate (playerBullet, transform.position, Quaternion.identity) as GameObject;
     clone.rigidbody2D.velocity = new Vector3(0,bulletSpeed,0);

     Transform muzzle = Instantiate (muzzlePF, firePoint.position, firePoint.rotation) as Transform;
     muzzle.parent = firePoint;

     //set up random size for the 'muzzle flash'
     //don't want this now should use the same size for every shot
     //...maybe
     //float size = Random.Range (.6f, 1f);
     //muzzle.localScale = new Vector3(size, size, size);
     Destroy (muzzle.gameObject, .04f);
   }//end Shoot() function

And thankyou so much for coming up with a solution to my problem it is very much appreciated :smile:.

And the, However, I can give you a not so “perfectly problem solving” line, had me rolling on the floor.

Ok, then, the code I showed up there is the solution.

By not so “perfecly problem solving”, I meant you may had something in Shoot(); that could affect my solution (Just in case)

1 Like

So my question is, what is better for a shoot script, FixedUpdate or Update? Why? What are some different scenarios to where one may be better than the other?

From my understanding FixedUpdate should be used if the object is using physics and that the Rigidbody is set to Dynamic. Though that could be totally wrong, I often am when it comes to Unity :p. If the object is kinematic Update seems to work just fine.

I do remember though going through a tutorial on YouTube that had both an Update and a FixedUpdate in the code for different things on a Player object. Update to control the SetBool and SetFloats for animation and FixedUpdate to control the Physics thingies. I imagine there would be a better way to do it, but, Unity seems to have some quirks and I haven’t learned anything in a structured manner.

Yeah, FixedUpdate() is in sync with physics from what I understand it. The docs say to use it with that.

There’s also LateUpdate(), which is where they recommend you implement your camera changes. It could be a good idea to check all input in Update(), then act upon variables set based on input in LateUpdate(), where you do your movement, firing and finally have the camera follow correctly.

LMAO! I hear ya bro! I’m in the same boat, but I’m piddling around with controls and trying to get a better understanding of what’s happening. What I noticed was my movement controls work perfectly in FixedUpdate, but my shoot script was erratic within the FixedUpdate, so I created the Update function for the shoot function and FixedUpdate for the movement and jump aspects.
However, I didn’t realize that changing the settings to Dynamic would alter the functionality of the FixedUpdate and the way it reads a rigidbody object. Very interesting to learn!
I just recently been dabbling with 2D programming, and I was surprised to see the difference. I thought it would be easier than 3D lol
About the same, overall. Anyway, thanks for the response!

I have seen something similar where a smooth follow script in 3D environment used a FixedUpdate to directly update the position, but used a LateUpdate to give a slight camera lag in following. This way the player wasn’t always in the middle of the screen. Something like that.
But wow! I have a lot to learn about these somewhat simple built-in functions! I originally thought that FixedUpdate was solely for calculations. You know, timers and stuff of that nature. Until recently, I just used Update for everything lol