Skip to content

How do I move a character in 2D?

Godot 4.x

Create a new scene with this structure:

  • PlayerCharacterBody2Dhas scriptthe script goes here
    • Sprite2DSprite2D
    • CollisionShape2DCollisionShape2Dgive it a shape

Give the Sprite2D a texture. The default icon.svg is fine for now. Then select the CollisionShape2D, pick a shape in the Inspector such as RectangleShape2D or CapsuleShape2D, and resize it to fit the sprite.

Attach a script to Player:

player.gd
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 move the player in eight 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 four actions: move_left, move_right, move_up, move_down. Assign both the arrow keys and WASD to them, then use those names instead of the ui_ ones:

player.gd
var direction := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
var direction := Input.get_vector("move_left", "move_right", "move_up", "move_down")

The ui_ actions are meant for menus. Keeping your own actions separate means a UI change later won’t break your movement.