Asteroids – Moving an Object with Inputs
Last time we looked at how we set up inputs in Unity. In this part we will apply those inputs to a script to allow us to control our ship.
Open up MyScript. We are going to add two new void methods. Call the first one RotateShip and call the second one MoveShip.
In this part we will just focus on the MoveShip method.
Add an if statement to MoveShip.
What do we put for the condition? We need to use a function built into Unity called Input.GetAxis. This function looks up the input and returns it’s value. We will be looking up the Vertical axis first. We need to check it is not 0 but we also need to check if it is above or below zero to determine our direction.
So how do we do that? We use two conditions (one for less than zero and one for above zero) with an OR operator between them.
So now we can retrieve the input, we need to do something with that input.
Basic physics tells us distance = speed * time. We have playerSpeed and we can get time from the C# function Time.deltaTime but that does not tell us the direction we need to move in.
The direction comes from whether the value of the Vertical input is positive of negative. We can therefore multiply our distance value by our Vertical value to find the direction.
As the ship will be moving in the Z axis lets declare a new float within our if statement called z. Set this equal to playerSpeed multiplied by Time.deletaTime multiplied by Input.GetAxis(“Vertical”).
Calculating z alone does not allow us to move the ship. We need to use the function transform.translate. This is a built in function which is very useful for moving objects. It requires a Vector3 so we need to pass it (0, 0, z). We do not want it to move in x or y hence the first couple of zeros.
So how do we move our ship sideways? Let’s add two new conditions to our if statement. If Input.GetAxis(“SideWays”) < 0 OR Input.GetAxis(“SideWays”) > 0. We will add an OR operator between our current conditions and these new ones.
The ship will move in the x axis when the SideWays inputs are pressed. Like we did with z, declare anew float x and calculate it with the same values as z, except this time use the SideWays input instead of the Vertical input.
All that remains is for us to change our translate function to (x, 0, z). That way the ship can move diagonally if both Vertical and Sideways inputs are pressed.
To make this work we just need to call the MoveShip method in the Update function.
Press play and you should be able to move the ship around with W, S, Q & E. If you are finding the movement too slow, just simply stop the game, increase the playerSpeed in the inspector and press play again until you are happy.
In the next part we will look at rotation of our ship.