Playing with Thrusters in Unity
Objective: use Input.GetKey to temporarily increase the speed of the Player and change the appearance of its thrusters, returning everything to its previous state once the same key is released.
I want to give the Player an increase in speed (thrusters) when pressing down the Left-Shift key on my keyboard. These are the steps I took:
→ Detect the Left-Shift key input;
→ Change the Scale of the thrusters to give the Player a visual cue that the thrusters have been activated. Return the Scale back to normal upon release of the Left-Shift key.
→ Increase the Player’s speed to 10.0f when Left-Shift is detected. Return the speed to its previous value (default value or value set by the Speed PowerUp) once Left-Shift is released.
The first step: use (Input.GetKey(KeyCode.LeftShift)) as a condition to change the transform’s scale. I solved this by creating the ThrustersScale script and attaching it to the two children (left and right thrusters). For the time being, I hard-coded their default values, as well as their increase in scale whenever a Left-Shift key is detected.
I then returned to my Player script and added the following two IF statements to the Update() method.
The first one, like the ThrustersScale script, looks for Left-Shift key input, and when held down executes the PlayerThrustersActivate() method.
The second one looks for the Left-Shift key to be released, upon which it executes the PlayerThrustersDeactivate() method.
PlayerThrustersActivate() simply hard-codes the _speed value to 10.0f. I felt it was a reasonable speed since anything much higher made the movements of the Player harder to control.
PlayerThrustersDeactivate() needed to consider whether or not the Player had collected a Speed PowerUp. That particular PowerUp, in my rendition, multiplies the default speed (5.0f) by a factor of 1.75f which equates to 8.75f. The Speed PowerUp has a lifespan of 5.0f seconds, and I used the _isPlayerSpeedBoostActive bool to verify its state. If TRUE, it uses the default _speed value of 5.0f and multiplies it by its _speedMultiplier (1.75f). This prevents the _speedMultiplier from further increasing the Player's speed beyond 10.0f when he collects a Speed PowerUp while engaging his thrusters.
Summary: By holding down the Left-Shift key, your Player speed has by default doubled momentarily. The most appealing visual cue, other than the apparent increase in movement speed, is the scaling of the Player thrusters to indicate that they are engaged.
I hope you will find this article useful in your own project. Thanks for reading :)