My aim is to allow my player to shoot 3 bullets at a time. Between shooting these 3 bullets the player should wait a very small interval (so that they don't all get fired at the same time) - call this gunLocalCooldown
. After shooting these 3 bullets, the player should wait a much longer interval - call this gunGlobalCooldown
. I also have a boolean canShoot
that must be true for a bullet to fire (i.e. when the gun is off cooldown).
Here is the code responsible for this in Update()
:
// If space is pressed, the gun is off local cooldown and the player can shoot
if (Input.GetKey (KeyCode.Space) && Time.time >= gunLocalCooldown && canShoot) {
// Bullet prefab
Rigidbody bPrefab = Instantiate (bulletPrefab, transform.Find ("Bullet").position, Quaternion.identity) as Rigidbody;
bPrefab.AddForce (transform.up * bulletForce);
gunLocalCooldown = Time.time + 0.12f;
bulletCounter++;
// If 3 bullets are shot, wait for gunGlobalCooldown then reset counter to 0 and allow him to shoot
if(bulletCounter == 3) {
gunGlobalCooldown = gunLocalCooldown + 0.8f;
if(Time.time >= gunGlobalCooldown) {
gunGlobalCooldown = Time.time + 0.8f;
canShoot = true;
} else {
canShoot = false;
}
bulletCounter = 0;
}
}
What happens right now: after player shoots 3 bullets he can no longer shoot. The problem is that after canShoot is set to false, it is never set to true again (it should be set to true if the player is able to fire 3 bullets again) - and after playing around with this code for a while I still can't figure out how to do this.
As well as this, I want the player to be able to fire 3 bullets again if he shoots even 1 or 2 bullets as long as the global cooldown is complete.
Any ideas?