Now we can move our ship forwards backwards and side to side we should make it so our ship is able to rotate.
Open up MyScript. In the RotateShip method we need to add an if statement just like our MoveShip method. However this time we will be looking for the “Horizontal” input.
So how are we going to get our ship to rotate? Well we will need to know how much we want to rotate by so we should declare a new float called angle. But what do we set this to? Like our linear movements this will be dependent on our input and our time so we can make it equal to our input multiplied by Time.deltaTime.
We can now use a built in function to rotate the object; transform.Rotate. We will pass it (0f, angle, 0f).
Why do we pass it these values? Well we want to rotate our ship around the Y axis. The first 0f represents the X axis and the one at the end represents the Z axis. We do not want to rotate in these axes hence their value should be zero. We calculated the angle we want to rotate around Y and therefore we can pass it straight into the Y axis value.
In the Update method we need to call our RotateShip function. Do this before the MoveShip method as we want to move the ship in the direction of our applied rotation. If it was after the MoveShip method the movement direction would always be one frame behind the rotation direction.
Now hit play and try to rotate the ship.
It rotates very slowly! That is not what we want.
To fix this we need to add a multiplication factor to our angle calculation, just like we did with playerSpeed in our movement calculation. Add a new public float called turningSpeed at the top of the class and set its default value to 100 (I found this was a reasonable speed).
Multiply our current angle calculation by this turning speed.
When we press play now the ship rotates at a much better rate. Play around with turningSpeed and find a value you like.
You should also notice the ship moves in a direction relative to its rotation which is exactly what we want.
In our RotateShip and MoveShip methods, the if statement’s conditions are very long. There is a way to simplify them so that the RotateShip if statement has only one condition (i.e no OR operator) and the MoveShip method could have two with an OR operator in between them. Can you work out how to simplify them? I will reveal the answer in the next part.
Up until now the learning has been very passive but if you want to be able to code and make games in Unity you will need to be able to actively work out how to make your own scripts. I will be giving these small active tasks every now and again to try and reinforce the content of my tutorials. I hope you enjoy :).