2D Character Setup in Unity — Movement

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.

  1. The speed the Player will move at horizontally on the screen.
  2. The force to add to the Player’s y-axis velocity when jumping.
  3. The Layer, the Player’s Raycast, will look to know if it is on the ground.
  4. A reference to the Rigidbody2D on the Player.
  5. 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.




Unity Developer, Software Engineer, Game Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Software Development Podcasts in 2021

Control Raspberry-pi’s GPIO pins from an Android

Underscores in Python

GooD: In this week 2 things were happen with me .

Visualize Your Business Communications History

Optimize Docker Image via Multi-Stage Builds

Struggles to Reach

Version Control Will Save Your Day

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
Kyle W. Powers

Kyle W. Powers

Unity Developer, Software Engineer, Game Developer

More from Medium

Creating a Physics Based Character Controller from Scratch in Unity

Making a RTS game #39: Boosting our game scene (Unity/C#)

Damage VFX using Animated Sprites in Unity

Journal 139 — Unity Project Development Part 1–2.5D Shooter