Question by
chaosninja7 · Sep 23, 2015 at 08:43 PM ·
scripting problemgun scriptfire1
Trying to make a alternating fire script for twin gun starfighter ( JAVA ). But both still fail to alternate and they fire at the same time.
var leftBarrel: GameObject;
var rightBarrel: GameObject;
private var shotIsLeft: boolean;
private var shotIsRight: boolean;
var plasmaShot: AudioClip;
var projectile: Rigidbody;
var projectileSpeed: float = 5;
var fireRate : float = 0.5;
private var nextFire : float = 0.0;
function Start ()
{
shotIsLeft = true;
shotIsRight = false;
}
function Update ()
{
if (Input.GetButton("Fire1") && Time.time > nextFire && shotIsRight == false)
{
nextFire = Time.time + fireRate;
GetComponent.<AudioSource>().PlayOneShot(plasmaShot);
var cloneLeft = Instantiate(projectile, leftBarrel.transform.position, leftBarrel.transform.rotation);
cloneLeft.velocity = transform.TransformDirection(Vector3(0,0,projectileSpeed));
shotIsLeft = false;
shotIsRight = true;
}
if(shotIsLeft != true)
{
nextFire = Time.time + fireRate;
GetComponent.<AudioSource>().PlayOneShot(plasmaShot);
var cloneRight = Instantiate(projectile, rightBarrel.transform.position, rightBarrel.transform.rotation);
cloneRight.velocity = transform.TransformDirection(Vector3(0,0,projectileSpeed));
shotIsLeft = true;
shotIsRight = false;
}
}
Comment
Best Answer
Answer by etopsirhc · Sep 23, 2015 at 09:58 PM
the main problem is fairly straight forward you are checking each barrels fire separately but when one fires, it cycles so the other is true, cycling it back to the beginning again. to fix this check the time separate from the barrels, and use an else with it. i also changed it to use delta time instead of time since the game started.
private var shotIsLeft: boolean;
var fireRate : float = 0.5;
private var nextFire : float = 0.0;
function Start ()
{
shotIsLeft = true;
}
function Update ()
{
nextFire += TIme.deltaTime;
if (Input.GetButton("Fire1") && nextFire >= fireRate )
{
if (shotIsLeft == true){
fire left barrel
shotIsLeft = false;
}else{
fire right barrel
shotIsLeft = true;
}
nextFire = 0f;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612034820im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity crashes because of a certain function 0 Answers
How to make my gun do damge and destroy a object? 1 Answer
script causes unity to crash 0 Answers
Gun won't face target 0 Answers
my fire script doesn't work properly 1 Answer