Unity: Adding a player-controlled speed boost
Our game currently has a speed boost powerup that is collectable, but it would be good to add a speed boost that is directly controlled by the player. Here’s how.
The objective with this feature is to speed up player movement as long as the left shift key is pressed. If a speed boost powerup is collected, that should overrule the key-based boost and shouldn’t allow an even higher speed.
First off, here are the variables involved; some of them were already set up for the speed boost powerup:
_basePlayerSpeed allows us to a) adjust in the inspector and b) have a constant speed to return to after any adjustments; this could just be a const but we’ll leave it for now. _playerSpeed is what we will use for movement calculations and boost adjustments.
In our Update method, we check for the left shift key and apply the speed multiplier:
Using GetKey we will always have the multiplier applied with the left shift key down. We also check that the speed boost powerup is not active. To ensure we return to the normal speed, we add an else to our if to return the speed to the base speed, if the speed boost powerup isn’t active already.
Our speed boost powerup logic now looks like this. To prevent the speed increasing too much and to separate the left-shift speed boost, we ensure that the speed is reset to the base speed before then being multiplied again.
Because we check for left shift every frame using GetKey, holding shift while the boost is active will just mean our player will continue at the increased speed once the powerup has finished.
Later on we can add a power bar mechanic and possibly damage the player if it runs out, or we can removed the powerup. For now, we’ve achieved what we intended.