Unity 2D Player Movement Tutorial | Unity Tutorial
In this Unity 2D player movement tutorial, you'll learn how to set up a player character with smooth horizontal movement and jumping mechanics. We'll guide you through creating a player GameObject, scripting basic movement controls, and adding jumping with ground detection. Additionally, we’ll show you how to prevent unwanted rotation for a stable gameplay experience. Perfect for beginners and those looking to enhance their 2D game skills.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
Unity Projects - ON SALE!!!
1. Water Sort Puzzle 9000 Levels
2. Ball Sort Puzzle 9000 Levels
3. Sling Shot
=========================================================
Scripts:
PlayerController.cs
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
public Transform groundCheck;
public LayerMask groundLayer;
public float groundCheckRadius = 0.2f;
private Rigidbody2D rb;
private SpriteRenderer spriteRenderer;
private Vector2 moveDirection;
private bool isGrounded;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
private void Update()
{
// Input handling
float moveX = Input.GetAxis("Horizontal");
moveDirection = new Vector2(moveX, 0).normalized;
// Check if player is on the ground
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
// Jump input
if (isGrounded && Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
// Flip player sprite based on movement direction
if (moveDirection.x > 0)
{
spriteRenderer.flipX = false;
}
else if (moveDirection.x < 0)
{
spriteRenderer.flipX = true;
}
}
private void FixedUpdate()
{
// Apply movement
rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);
}
}