Thrusters Activate!

Objective: Increase the speed of your player while holding shift

Sprint is a function in games that is so common it is noticeable immediately and frowned upon by many if the feature is not included. To simplify what sprint does, it give your player a boost in speed while holding a a button. In this tutorial the button in question will be the left shift key.

To begin, we need to make a variable to represent the sprint speed.

We are going to hard set a value to this variable so we can add the value later.

Now we need to go to the method we use to calculate our player’s movement.

This is where we will implement the sprint function we want to use. We want to hold a button to make our player move faster. To do this we need to use an if statement with the input we want to use.

With this Get Key Down the code will be active as soon as the left shift key is pressed down. We want to add the sprint speed variable we created to our base speed variable.

We are not finished. If we left the if statement as it is then you could add to your speed every time you pressed the left shift key.

As fun as that can be, the desired effect is to have the speed return to the normal base speed when we let go of the shift key to do this, we can use another if statement.

This Get Key Up will take effect on the last frame that the button was pressed on, i.e. as soon as you let go of said key.

We want to remove the sprint variable from the base speed variable.

Now the sprint is only called while the left shift key is pressed and as soon as you let go the player returns to its normal speed.

There you have it. If you want to go faster, you can raise the value of the sprint speed variable to you desired speed. While using this on off functionality it will work with a powerup you may have for speed, it will add the sprint value to the powerup value. Now your player can sprint. Remember, don’t be afraid to experiment with your code, and I’ll see you in the next tutorial.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store