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

The Importance of “Soft Skills” for Developers

Fsociety Hacking Tools Pack — A Penetration Testing Framework

IOT Hotel Room Protection (WIP)

Network Fundamentals of Docker Containers

Simple Password Generator

How to Install Apache Cassandra on Windows 10

Build a web-scraped time-series application with AWS CDK in TypeScript — Part 1

Enhance Spark performance using Delta Lake and Delta Caching

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

How to get GIT Bash for Unity

2D Mobile: Loot System

Damage VFX using Animated Sprites in Unity

Creating Elevator in Unity — Part 3: Moving Elevator.