Day 31 — Improvments: Thrusters

Hey and welcome!

In the next few articles here we’re going to be looking into adding improvements to our game with the knowledge we’ve learned so far. While working on them I was starting to think that some of the improvements I was implementing were not the most efficient and that there could be potentially a better way to go about things so it will be interesting to revisit this code later on when I’ve gotten my hands on more knowledge working with C# in Unity.

Let’s start things off with our thrusters, currently they only have a visual cue and don’t really do anything so we’re going to change it so that if you press and hold the left shift key it will boost the player’s speed by a little bit less than what our speed powerup does so that the powerup doesn’t become redundant.

So let’s start off with some code from our player script:

private float _thrusterSpeed = 12.0f;if (_collectedSpeed == false && Input.GetKey(KeyCode.LeftShift) == false)
{
transform.Translate(direction * _playerSpeed * Time.deltaTime);
}else if (_collectedSpeed == true){ transform.Translate(direction * (_playerSpeed * _doubleSpeed) * Time.deltaTime);}else if (_collectedSpeed == false &&Input.GetKey(KeyCode.LeftShift)){ transform.Translate(direction * _thrusterSpeed * Time.deltaTime);}

Now there’s a fair amount going on here but the main takeaway is that we’ve added a new else if statement that runs if the LeftShift key is being held down and that the speed powerup hasn’t been picked up. I’ve set it as a flat speed this time of 12.0f instead of multiplying an amount by the player speed as I wanted to keep both separate so it’s easier to debug if one of them is coming up with an issue.

Also notice that Input.GetKey() is being used instead of Input.GetKeyDown this is what you put in so that Unity can recognise if a key is being held down rather than just being pressed the one time. Lastly we’ve added an extra check in our if statement for the regular movement, now the player will only move at regular speed if the LeftShift isn’t being pressed and the speed powerup isn’t collected.

This is necessary as you can come across an issue where both transform.Translate will run at the same time and compound the speed higher than desired.

In order to see it more clearly in action I’ve also set the thruster object to false and set it to active in our if statement where we press LeftShift by using _thrusterObject.SetActive(true). Don’t know about you but I enjoy using the tools and knowledge that I have on hand to complete a task set forme since you may have noticed that the code was all stuff we’ve seen before which is going to be a running theme for the rest of these improvements.