I’m working on a space shooter and right now the player can shoot as fast as you can push the space bar and I just wanted to know how I would go about changing my script to limit the players rate of fire. All I have right now is just a basic piece of code that fires a bullet prefab, and the bullet prefab moves up the screen and checks for collisions with enemies then adds score.
this is what I have right now for the player shooting:
If (Input.GetKeyDown(“space”)){
var tempBullet: Rigidbody;
tempBullet = Instantiate(bullet, transform.position, transform.rotation);
private var allowfire : boolean = true;
var tempBullet: Rigidbody;
function Update()
{
if((Input.GetButtonDown)&&(allowfire))
{
Fire();
}
}
function Fire()
{
allowfire = false;
tempBullet = Instantiate(bullet, transform.position, transform.rotation);
yield WaitForSeconds(rate with which you want player to fire);
allowfire = true;
}
public class ShootBullets: MonoBehaviour {
public GameObject spawnPoint;
public Rigidbody projectilePrefab;
public float speed;
public float fireRate = 1.0f;
private float lastShot = 0.0f;
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
if (Time.time > fireRate + lastShot) {
Rigidbody hitPlayer;
hitPlayer = Instantiate (projectilePrefab, transform.position, transform.rotation) as Rigidbody;
hitPlayer.velocity = transform.TransformDirection (Vector3.forward * speed);
lastShot = Time.time;
}
}
}
}
This code works perfectly for me. It allows for the speed of the projectile to be changed as well as the fire rate. The only thing I noticed was that the player cannot shoot immediately once the game is started. Minor setback, however, I am interested in figuring out a way to allow the player to shoot once the game starts, and THEN be limited.