Hey everyone.
As you know, the aim of this lecture is to spawn projectiles based on a firing speed (and some other things).
The method in the lecture (using InvokeRepeating) is great and simple. However, it gives the player the ability to bypass the shooting speed, and potentially shoot really really fast by spamming the space-bar.
Now, it might not be elegant, but I’ve found a solution:
- We set up our variables, much like in the lecture, with our projectile prefab, firing rate and projectile speed:
public float fireRate;
public float projectileSpeed;
public GameObject projectilePrefab;
private float nextFire;
Notice however, that we also add a private float called nextFire. This will make sense later.
- In our update method, we check to see if the player is holding down the space key. For this, we use
Input.GetKey
void Update () {
if (Input.GetKey(KeyCode.Space)) {
FireProjectile();
}
}
If the play is holding down space, we call the method FireProjectile.
- In our
FireProjectilemethod, we will now do our calculations. Ignore the if statement for now, and imagine we just run the code inside of it.
void FireProjectile() {
if (nextFire <= Time.realtimeSinceStartup) {
float nextFire = Time.realtimeSinceStartup + fireRate;
GameObject projectile = Instantiate(projectilePrefab, this.transform.position, Quaternion.identity) as GameObject;
projectile.rigidbody2D.velocity = new Vector2(0f, projectileSpeed);
}
}
When the method is called, the first thing we do is set the nextFire float to Time.realTimeSinceStartup. Time.realTimeSinceStartup is simply a float representing the amount of seconds since the game started. When we set nextFire to the real time plus our fire rate, we get the time at which the player is allowed to fire his/hers next projectile.
If we now consider the if statement again, it checks to see whether enough time has elapsed since the last projectile was fired. If not, we wont fire another one. If enough time has elapsed, we will fire a new one.
I hope this made sense, and was somehow useful. If there’s some part of this you don’t understand, please do not hesitate replying to this thread. I will answer all the question I can.
Best of luck, and keep on making awesome games!
-FP
