One of the earliest tasks in Unity is determining how to move a player or character in the game world, whether it’s 2D or 3D movement.
2D movement is typically handled by the keyboard WASD or arrow keys, to move up, down, left, and right.
Unity already provides within its Project Settings the basic movement using keyboard, mouse, and game controllers. We just need to access this movement with a basic C# script. In this example, we will prepare a script for keyboard movement.
- Create a project the 3D layout.
- Create a 3D cube and create a C# script and attach it to the cube. You can call it something such as “Player”. Eventually you can change this cube to your actual character, but for now we just want to make sure the basic movement works.
- Per the Input Manager, we want to access the “Horizontal” and “Vertical” movement.
- If you do some searches on Unity documentation for horizontal and vertical movement, you can find reference to the Input.GetAxis(“Horizontal”) and Input.GetAxis(“Vertical”) interface options.
- The values vary from -1 to +1, meaning movement to the right (+ direction) is +1, and movement to the left (- direction) is -1, and similarly for the up-down movement. To see this in action, let’s make a public float variable horizontalInput and verticalInput so they are visible in the Inspector, and set them equal to Input.GetAxis statements above. This must be done in the Update method to see the changes realtime. I also created a speed variable to be able to adjust how fast the movement is.
6) Now to apply this movement, we need to use the transform.Translate script, which per Unity documentation means: “Moves the transform in the direction and distance of translation.” In C#, we need a Vector3, multiplied by a user selected speed, multiplied by Time.deltaTime, in order to make the movement occur in real time.
7) In C#, to keep the code relatively tidy, I will go ahead and define a Vector3 called direction, and fill in the X and Y movements with the earlier defined variables horizontalInput and verticalInput, and set Z to 0.
Now back to Unity, and run Playmode to test it out!
There are numerous options for player movement. From what I have learned from experimentation and reading up on discussion boards and Unity documentation, there is no one right answer for the “best” way to move a character.
Another option for movement is to use an If-Then method to check for Input.GetKey(KeyCode.LeftArrow), which can be defined as movement in the Vector3.Left direction multiplied by speed and multiplied by Time.deltaTime. You can repeat this approach for other arrow keys, or define your own keys for movement.
You can also apply Physics to movement, include collision effects while moving around, and gravity, such as if you define a jump method when hitting the Spacebar.
Unity also includes a built-in CharacterController which can be used for movement in first person and third person games.
Thank you for stopping by!