How do I move a character in 2D?
Set up the scene
Section titled “Set up the scene”Create a new scene with this structure:
PlayerCharacterBody2D
the 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.
Add the script
Section titled “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()using Godot;
public partial class Player : CharacterBody2D{ private const float Speed = 300.0f;
public override void _PhysicsProcess(double delta) { Vector2 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down"); Velocity = direction * Speed; MoveAndSlide(); }}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.
Use WASD too
Section titled “Use WASD too”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:
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.