This article will show how to create and set up a 2D character in Unity. The 2D character will be able to move around the screen and jump.
The Player script needs a few variables to control the movement of the character.
- The speed the Player will move at horizontally on the screen.
- The force to add to the Player’s y-axis velocity when jumping.
- The Layer, the Player’s Raycast, will look to know if it is on the ground.
- A reference to the Rigidbody2D on the Player.
- A reference to the Sprite Renderer for the Player to control the facing.
This method flips the Player’s sprite based on the passed in horizontalInput if it is not already flipped. The sprite is reversed on the x-axis by using the Sprite Renderer’s flip X bool. The Renderer also has a bool to flip on the y-axis.
This method is using a Raycast to detect if the Player is touching the ground. The Raycast starts at the center of the Player GameObject aimed down. It travels 0.75 units and only returns true if the Collider hit is on the Ground Layer.
The CalulateMovement method controls the movement and jumping of the Player. Input from the Horizontal Axis is multiplied by speed to create the velocity applied to the Rigidbody. If the spacebar is pressed and CheckGrounded returns true, the y-axis of velocity is set to the jump force. The horizontal input is passed to the Flip method to see if the sprite needs to be flipped.
The Player has a Box Collider 2D and Rigidbody 2D components, and the Ground Layer variable is set to the Ground layer. The Floor GameObject, which has the Tile Map collider for the scene, is set to the Ground layer.
Now the Player moves around and flips to face the direction of movement, and when touching a Collider set to the Ground layer, the Player can jump.