Making A Moveable Player Object
Objective: Make A Moveable Player
To begin moving a player, we need to know about transform.Translate(), Vector3.right, Vector3.up, and Vector3.forward. First transform.Translate() is a function that will allow you to move an object based on a vector3 that is input into it. Vector3.right is a variable equivalent to Vector3(1,0,0), Vector.up is the same as Vector3(0,1,0), and finally Vector3.forward is Vector3(0,0,1).
Now to start making our player move, we can type “transform.Translate(Vector3.right);” into the Update function.
If you then save and go back to Unity, and press play, you will see that your Player moves away in the direction you specified very quickly. The reason this happens is because it is moving the Player along the Vector3 that you input every frame the game is running. So if your game is running 60 frames per second, that means every second it is adding your Vector3 input times 60.
To slow this down, we will need to make it work off real time movement and not frames per second movement, we need to use Time.deltaTime. By multiplying our Vector3 movement x Time.deltaTime, it brings us down to moving in real time. Time.deltaTime basically translates the frames per second, into real world seconds, minutes, and so on. To do this we would simply type “transform.Translate(Vector3.right * Time.deltaTime);”.
Going back into Unity now, we can test this and see that our Player object is moving much slower.
Now that we have our Player moving, we can now control the speed at which the Player moves at. To do this, we can add a variable to the class for Player speed. To do so, under the class of your script, just type “public float playerSpeed” and to start we can give it a default value as well. Once this is done we simply add our playerSpeed variable to our movement and multiply it by our Vector3.