Player movement

Objective: Create a player for 2D Unity game that can move and jump.

Player movement showing box collider as green frame and raycast in yellow.

Before adding the player make sure the ground tilemap or Floor has a rigidbody 2D with body type static and box collider with used by composite checked. Make sure the floor layer is set to Ground.

Floor of the dungeon.

Create an empty game object named Player, and add a new script called Player. Also add a rigidbody 2D freezing rotation under constraints and a box collider.

Player component setup.

Drag Player sprite Idle_0 into hierarchy as a child of the Player, renaming the sprite to Sprite. Adjust the size of Player’s box collider to fit the model. The Player script needs access to _rigidbody which is assigned in void Start(). The _playerVelocity, _jumpVelocity, and _distToGround can be adjusted in the inspector.

Player variable assignment for movement.

The Movement() method is called in void Update() and is shown below. Movement first assigns the _vertical to the current rididbody.velocity.y then uses Physics2D.Raycast limited by _distToGround to detect the ground. This distance needs to be fairly precise and just a little larger than half the box collider’s Y size minus the Y offset. By using the raycast in the if statement it will automatically be reset when the player leaves the detection distance. If this ray cast is not null then the Player jumps if the space bar is pressed, and can move left and right by pressing A and D keys.

Movement method in Player script.

The Debug.DrawRay command allows the visualization of the raycast in the scene view. In the gif at the top of this article shows that the yellow line downward disappears when the raycast is null, visualizing how the if statement works.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store