Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silver-hornet/a65640d97a1c2de3691f53ed8afd2d2d to your computer and use it in GitHub Desktop.
Save silver-hornet/a65640d97a1c2de3691f53ed8afd2d2d to your computer and use it in GitHub Desktop.
2D Top-Down Character Movement (grid based movement, with RigidBody2D)
// This script enables simple, 2D top-down grid based character movement.
// Ensure you have added a RigidBody2D component in the Inspector and have set its Body Type to Kinematic.
// The player only moves in units of 1 on the x or y axis and is unable to move diagonally or continuously.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] Rigidbody2D rb;
void Update()
{
if (Input.GetKeyDown(KeyCode.RightArrow))
rb.MovePosition(rb.position + Vector2.right);
else if (Input.GetKeyDown(KeyCode.LeftArrow))
rb.MovePosition(rb.position + Vector2.left);
else if (Input.GetKeyDown(KeyCode.UpArrow))
rb.MovePosition(rb.position + Vector2.up);
else if (Input.GetKeyDown(KeyCode.DownArrow))
rb.MovePosition(rb.position + Vector2.down);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment