Updating the Shooting Logic
Let’s tweak the behaviour for shooting projectiles with the laser weapon.
Currently when a key is pressed, our weapon only shoots once. However I’d like to introduce a more fluent shooting logic so that if the player holds a key down, projectiles are being fired continuously.
Objective:
Making the Player shoot for the entire duration a key is held and after each time a projectile has been fired, add a small delay.
Necessities:
- A new GameObject “YourWeapon” attached to the Player GameObject.
- Either a new script “Weapon” or the previous one we used, but now attached to “YourWeapon”.
- A simple sprite texture for the Laser Projectile.
In case you are following along, make sure to remove the old Fire Projectile Logic from our player script. We will store the Logic on the Weapon that is attached to the Player, rather than on the Player itself.
Solution:
It’d be more efficient to convert our shooting logic into a coroutine and not have it run persistently in the Update() function. We initialise a while loop and while condition is true the code is ran in which our FireProjectile() method is passed and a delay is added.
Logic:
First we need to add a couple member variables. One that stores a reference to our Projectile Prefab, another one to initialise a custom Spawn Position for the projectile and another one that will define our delay between shooting projectiles.
Then assign a new Vector3(“your spawn position”) and run it in start depending on where you want to instantiate the projectile in game.
Our current FireProjectile() method;
Just to make sure it’s the Player that is pressing the key and to check if there is a Player at all let’s grab a reference to it which we can pass true or false in our next step.
Now let’s fabricate a Coroutine in which we call the function and add a delay each time it has ran the code block in the while condition is true loop. We can declare the fire delay outside of this routine by exposing it in the name.
At last we have to initialise the FireProjectileRoutine(float delay) in the Start() function. We can now pass in a value for our fire delay.
I think shooting is a lot more fluent now, by giving our weapon basic modular characteristics it’ll be slightly easier to modify it for different purposes in the future.
Weapon.cs;