- Home /
Question by
davidflynn2 · Oct 27, 2012 at 06:10 AM ·
bullets
Preventing Rapid Fire
When I press the button for my weapon fire I can spam it firing bullet after bullet, I would like to limit this to add like a 2 second delay in bettwen shots and I am not sure how to add this in.
This is my fire code.
var missile : GameObject;
var missile2 : GameObject;
var missile3 : GameObject;
function Update () {
if (Input.GetMouseButtonDown (0))
{
var position : Vector3 = new Vector3(0, 0, 0) * 10.0;
position = transform.TransformPoint (position);
var thisMissile : GameObject = Instantiate (missile, position, transform.rotation) as GameObject;
//Physics.IgnoreCollision(thisMissile.collider, collider);
var position3 : Vector3 = new Vector3(0, 0, 0) * 10.0;
position = transform.TransformPoint (position3);
var thisMissile3 : GameObject = Instantiate (missile3, position3, transform.rotation) as GameObject;
}
else if (Input.GetMouseButtonDown (1))
{
var position2 : Vector3 = new Vector3(0, 0, 0) * 10.0;
position = transform.TransformPoint (position2);
var thisMissile2 : GameObject = Instantiate (missile2, position2, transform.rotation) as GameObject;
//Physics.IgnoreCollision(thisMissile.collider, collider);
}
}
Comment
there is a massive discussion about basic timer matters on unityGE$$anonymous$$S.com
hope it helps
BTW never use "else if"
your best pattern there is if .. { blah return }
never use else if.
Best Answer
Answer by Jessespike · Oct 27, 2012 at 06:04 PM
A timer can work here.
var shootCooldown : float = 2; // Wait time between shots
var shootTimer : float; // Tracks the time since last shot fired
function Update () {
shootTimer += Time.deltaTime; // Keep track of passing time
if (shootTimer < shootCooldown) {
return; // Gun not ready to fire, prevent firing.
}
if (Input.GetMouseButtonDown (0))
{
shootTimer = 0; // Reset timer
var position : Vector3 = new Vector3(0, 0, 0) * 10.0;
...
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Make GUI.TextArea show up only when Left Ctrl pressed 1 Answer
A node in a childnode? 1 Answer