- Home /
Fooling Rate Of Fire C#
Hi again! I'm trying to prevent my player from shooting as fast as he can press the Space Key. I'm programming in C# right now and I find Coroutines a little bit too complex to handle. Instead, what I came up with is this:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public GameObject myProjectile;
public float nextFire = -1.0f;
void Start () {
nextFire = Time.time;
}
void Update () {
//SHOOTING
if(Time.time >= nextFire){
if(Input.GetKeyDown(KeyCode.Space)){
nextFire = nextFire+1;
myProjectile.transform.position = new Vector3 ( Player.position.x, Player.position.y, Player.position.z);
Instantiate(myProjectile);
}
}
}
}
This script works good in my 2d game project, except for one issue: Sometimes, when I press Space really really fast, I can shoot two or three times in a row no matter what the code says... especially when I intentionally pick up the peace to fool this limitation.
I tried to change the GetKeyDown with GetKey or GetKeyUp and nothing changes for the good.
It seems my solution is either wrong or incorrectly applied. Is this oversight somehow implied by my code and nothing can be done to solve this issue, apart from adopting a new solution? In this case, what would you suggest?
Thanks for your time!
Answer by robertbu · Oct 06, 2013 at 08:52 PM
The issue I see is not so much with rapid keystrokes, but one of how long you pause before you fire. Let me start with my suggested solution. Line 20 should be:
nextFire = Time.time + 1.0;
This means the user will have to pause one full second before firing again. Without this, imagine the player waiting 10 seconds before hitting the 'Space' key. He would then be aboe to fire 10 shots as fast as he could before nextFire would catch up to Time.time.
Ah! thanks a lot for pointing that out! it works perfectly now!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
rapid movement back and forth 1 Answer
Renderer on object disabled after level reload 1 Answer
Working projectile scripts do not work due to if condition 1 Answer