Last active
May 29, 2021 16:00
-
-
Save silver-hornet/a65640d97a1c2de3691f53ed8afd2d2d to your computer and use it in GitHub Desktop.
2D Top-Down Character Movement (grid based movement, with RigidBody2D)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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