Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Fire Rate Code.

Discussion in '2D' started by CelticKnight, Jan 20, 2017.

  1. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    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):
    1. [code=CSharp]
    2.  
    3. // Update is called once per frame
    4.     void Update () {
    5.         //deal with weapons - single burst or multiple
    6.         //outer if
    7.         if (fireRate == 0)
    8.         {
    9.             //Shoot ();
    10.             //inner if
    11.             if(Input.GetButtonDown("Fire1"))
    12.             {
    13.                 Shoot();
    14.             } //end inner if
    15.         }//end outer if for the else command
    16.         else
    17.         {
    18.             //inner if in the else function also using &&
    19.             if (Input.GetButton("Fire1") && Time.time > nextFire)
    20.             {
    21.                 //this below is unity docs example
    22.                 nextFire = Time.time + fireRate;
    23.                 Shoot ();
    24.                 //print ("coolio");
    25.             }
    26.         }
    27.  
    28.     }//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!!! :cool:.
     
    Last edited: Jan 20, 2017
  2. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    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:

    Code (CSharp):
    1.  
    2.  
    3.    float cooldownSeconds = [Whatever you want];
    4.    float cooldown;
    5.    int maxAmmo = [Whatever you want];
    6.    int ammo;
    7.  
    8.     void Update () {
    9.         if (fireRate == 0 && Input.GetButtonDown("Fire1"))
    10.         {   //Reduced to a single if, cause It does exactly the same
    11.             //And in my Opinion, looks better. (You might want not to
    12.             //in case you have anything else here that do needs the if)
    13.             Shoot ();
    14.         }
    15.         else
    16.         {
    17.             if (Input.GetButton("Fire1") && Time.time > nextFire && fireRate > 0)
    18.             {
    19.             //I added "&& fireRate > 0", because if not, this will run if the user decides
    20.             //to hold the button, as "GetButtonDown" only returns true the frame the button
    21.             //is pressed, and while its hold, is false, so the "else" will run, and so will this.
    22.                 if (ammo > 0)
    23.                 {   //If you have ammo
    24.                    nextFire = Time.time + fireRate;
    25.                    Shoot ();
    26.                    ammo--; //Explained by itself
    27.                 }
    28.                 if (ammo == 0)
    29.                 {   //If you no longer have ammo
    30.                    if (cooldown > Time.time)
    31.                    {   //If there is no cooldown (relatively)
    32.                       cooldown = Time.time + cooldownSeconds;
    33.                    }
    34.                 }
    35.             }
    36.         }
    37.  
    38.        if (Time.time > cooldown && ammo == 0)
    39.        {   //If the cooldown is over, and you have no ammo cause else this will run kinda always,
    40.            //as here we set the ammo to maxAmmo, and cooldown only happens when you run out
    41.            //of ammo, then you will be constantly fulling the ammo.
    42.            ammo = maxAmmo;
    43.        }
    44.  
    45.     } //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)
     
    Last edited: Jan 20, 2017
    CelticKnight likes this.
  3. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    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.
     
  4. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    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 :D. 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.

    Code (CSharp):
    1. public void Shoot(){
    2.      print ("We are in Shoot...");
    3.  
    4.      //play the sound???
    5.      audio.PlayOneShot(laserShot, 1.0f);
    6.  
    7.      //GameObject go = Instantiate (bulletThingy, firePointPosition, Quaternion.identity) as GameObject;
    8.      clone = Instantiate (playerBullet, transform.position, Quaternion.identity) as GameObject;
    9.      clone.rigidbody2D.velocity = new Vector3(0,bulletSpeed,0);
    10.  
    11.      Transform muzzle = Instantiate (muzzlePF, firePoint.position, firePoint.rotation) as Transform;
    12.      muzzle.parent = firePoint;
    13.  
    14.      //set up random size for the 'muzzle flash'
    15.      //don't want this now should use the same size for every shot
    16.      //...maybe
    17.      //float size = Random.Range (.6f, 1f);
    18.      //muzzle.localScale = new Vector3(size, size, size);
    19.      Destroy (muzzle.gameObject, .04f);
    20.    }//end Shoot() function
    And thankyou so much for coming up with a solution to my problem it is very much appreciated :D.

    And the, However, I can give you a not so "perfectly problem solving" line, had me rolling on the floor.
     
    Last edited: Jan 20, 2017
  5. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    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)
     
    Last edited: Jan 20, 2017
    CelticKnight likes this.
  6. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    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?
     
  7. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    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.
     
  8. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
    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.
     
  9. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    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!
     
  10. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    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