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;
	}
		
}

that's also didnt helped i know how to handle loops :P but it's don't working, if the loop just runs one time!

1 Answer

1

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;
         }
     }

Try modifying your syntax while(!(count == repetitions)) while(count != repetitions) Also, Is it in a Coroutine? It must be a coroutine for a yield to work.