How do I move a character in 2D?
Short answer: use a CharacterBody2D. In _physics_process, set its velocity, then call move_and_slide().
1. Set up the scene
Section titled “1. Set up the scene”Create a new scene with this structure:
Player (CharacterBody2D)├── Sprite2D└── CollisionShape2D- Give the
Sprite2Da texture. The defaulticon.svgis fine for now. - Give the
CollisionShape2Da shape in the Inspector, such as aRectangleShape2DorCapsuleShape2D, and resize it to fit the sprite.
2. Add the script
Section titled “2. Add the script”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.
3. Use WASD too (optional)
Section titled “3. Use WASD too (optional)”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")