- Home /
Timing Between each Gun Shot
I have a script for shooting and it shoots way to fast. how can i change the fire rate?
Here is the script:
var projectilePrefab:Transform;
var projectile2Prefab:Transform;
var strayFactor : int = 2; //for example
var strayFactorAim : int = 0.1; //for example
private var aiming : boolean = false;
function Update() {
if(Input.GetButton("Fire2")){
aiming = true;
}
else{
aiming = false;
}
if(aiming == false){
if(Input.GetButton("Fire1") ) {
var randomNumberX = Random.Range(-strayFactor, strayFactor);
var randomNumberY = Random.Range(-strayFactor, strayFactor);
var randomNumberZ = Random.Range(-strayFactor, strayFactor);
var projectile = Instantiate(projectilePrefab, transform.position, transform.rotation);
projectile.transform.Rotate(randomNumberX, randomNumberY, randomNumberZ);
projectile.rigidbody.AddForce(projectile.transform.forward * 10000);
}
}
if(aiming == true){
if(Input.GetButton("Fire1") ) {
var randomNumberX2 = Random.Range(-strayFactorAim , strayFactorAim );
var randomNumberY2 = Random.Range(-strayFactorAim , strayFactorAim );
var randomNumberZ2 = Random.Range(-strayFactorAim , strayFactorAim );
var projectile2 = Instantiate(projectile2Prefab, transform.position, transform.rotation);
projectile2.transform.Rotate(randomNumberX2, randomNumberY2, randomNumberZ2);
projectile2.rigidbody.AddForce(projectile2.transform.forward * 10000);
}
}
}
Answer by fafase · Nov 13, 2013 at 05:57 AM
your problem is that you are using Input.GetButton so every frame you get a new projectile.
You need to refrain that:
var fireRate:float;
var timer:float;
if(Input.GetButton("Fire1") && timer <= 0){
//Your shooting
timer = fireRate;
}else{
timer -= Time.deltaTime;
}
if(Input.GetButtonUp("Fire1"))
{
timer = 0;
}
fireRate is the frequency of shooting, when shooting timer becomes fireRate and you shoot. Then next round timer is greter than 0 so you cannot shoot but timer gets decreased. This will be until timer is smaller or equal to 0.
If you release the button, then timer is 0 so you can shoot without waiting.
What do you consider to be full auto? This code should shoot at a rate as long as you are pressing, semi auto is when you need to release each time to shoot. The last one is burst which shoots a limited amount of bullet per press of the trigger (I sound like a NRA member now...or a COD geek). So which are you looking for?
Answer by rooted · Nov 18, 2013 at 11:02 AM
Check out my post here for my search for a better machine gun. I'm quite happy the way it turned out. It's a bit tricky but very effective.
Your answer
Follow this Question
Related Questions
Basic Shooting Game 1 Answer
Bullet Script Help 3 Answers
Bullet does not move forward 1 Answer
A node in a childnode? 1 Answer
Animation & Script Help 2 Answers