PLayer Movement

Unity Game Development – 05 – Player Movement

In order to make the player move , we need to add a script to the Player GameObject, that takes care of the input from the user.

1. Getting player Input

The Input.GetAxisRaw(“Horizontal”) returns any movement values make by the user horizontally. This can be used to control the GameObject by setting its velocity appropriately in the relevant direction.

We can also get the other keys that were pressed, for example… Input.GetKeyDown(KeyCode.Space) checks if the Space bar was pressed. Using the combination of these 2 fields, we are able to determine if the user has moved vertically or horizontally.

2. Controlling Player Animations

As we have created several animation states previously, we can now use them to control the display on the screen.

We can Access the properties within the animation using the SetFloat , SetBool etc methods. This method allows transitioning between states , For example, to change the state from Player to PlayerRun, we can use animator.SetFloat("speed", 5f); Here the speed property is used as the condition to move from Player to PlayerRun.

3. Collision Detection

Set up a TileMap Collider and name the layer as “Foreground” . The layer number is 8 for the selected Layer. So now all the surfaces on the foreground layer are surfaces.

The player also has Rigidbody2D and a 2d Collider on it. As long as the gravity of the Foreground layer elements is set to 0, the player will be able to stand on the layer surfaces.

4. Raycasting

In order to make a jump , we first need to check if the player is already jumping or not. In order to determine this, we can create a RayCastHit2D and check if it has collided with objects on the Foreground layer number 8.. If the Ray has hit a target, it will return this information about the target that was hit.

To do this, use RaycastHit2D hitInfo= Physics2D.Raycast(transform.position, Vector2.down, 0.6f, 1 << 8);

5. Physics Materials

Apart from the other movement related tasks, we also encounter an issue at the edges, where the sprites tend to get stuck. IF we create a new Physics2D material and set the “Friction” to 0 , it will eliminate this error.

The player appears during running like shown below…

Below is the Idle Animation, where player has slight movements

And finally, this is where the plater jumps…