Skip to content

How do I move a character in 2D?

Short answer: use a CharacterBody2D. In _physics_process, set its velocity, then call move_and_slide().

Create a new scene with this structure:

Player (CharacterBody2D)
├── Sprite2D
└── CollisionShape2D
  • Give the Sprite2D a texture. The default icon.svg is fine for now.
  • Give the CollisionShape2D a shape in the Inspector, such as a RectangleShape2D or CapsuleShape2D, and resize it to fit the sprite.

Attach a script to Player:

extends CharacterBody2D
const SPEED := 300.0
func _physics_process(_delta: float) -> void:
var direction := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
velocity = direction * SPEED
move_and_slide()

Run the scene. The arrow keys now move the player in 8 directions, and it stops at walls instead of passing through them.

Input.get_vector returns a vector with a length of 1 or less, so moving diagonally isn’t faster than moving straight.

Open Project → Project Settings → Input Map and add your own actions: move_left, move_right, move_up, move_down. Assign both the arrow keys and WASD to them, then use those names in get_vector:

var direction := Input.get_vector("move_left", "move_right", "move_up", "move_down")