Unity How to Make Simple Player Movement

Follow below steps to create a moving and jumping player.

  • Create a player sprite/gameobject
  • Add a RigidBody2D component;
  • Freeze the (Z) Rotation of the RigidBody2D;
  • Add and position a CircleCollider2D component over the feet;
  • Add and position a BoxCollider2D component over the torso;
  • Add an empty GameObject called “GroundCheck” as a child to your player GameObject (select icon or label for it for better visibility in editor);
  • Position this below or on his feet;

Add this script to your player GameObject:

PlayerMove.cs
using UnityEngine;
using System.Collections;
 
public class PlayerMove : MonoBehaviour {
 
	float maxSpeed = 10f;
	float jumpForce = 300f;
 
	bool grounded = false;
	public Transform groundCheck;
	float groundRadius = 0.2f;
	public LayerMask whatisGround;
 
	// Use this for initialization
	void Start () {	
		GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.FreezeRotation;
	}
 
	// no need for * Time.deltaTime here	
	void FixedUpdate () {
		grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatisGround);
 
		if (grounded) {
			float move = Input.GetAxis ("Horizontal");
			Vector2 current = GetComponent<Rigidbody2D>().velocity;
			GetComponent<Rigidbody2D> ().velocity = new Vector2 (move * maxSpeed, current.y);
		}
	}
 
	void Update() {
		if (grounded && Input.GetKeyDown (KeyCode.Space)) {
			GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
		}
	}
}

Select your player and in the inspector do the following:

  • Put your player in the “Player” layer;
  • Drag the GroundCheck child to the GroundCheck transform slot;
  • In the whatisGround layermask select “Everything” and deselect “Player”;
Navigation
Print/export
Toolbox