Up to date

This page is up to date for Godot `4.1`. If you still find outdated information, please open an issue.

# 2D movement overview¶

## Introduction¶

Every beginner has been there: "How do I move my character?" Depending on the style of game you're making, you may have special requirements, but in general the movement in most 2D games is based on a small number of designs.

We'll use CharacterBody2D for these examples, but the principles will apply to other node types (Area2D, RigidBody2D) as well.

## Setup¶

Each example below uses the same scene setup. Start with a `CharacterBody2D` with two children: `Sprite2D` and `CollisionShape2D`. You can use the Godot icon ("icon.png") for the Sprite2D's texture or use any other 2D image you have.

Open `Project -> Project Settings` and select the "Input Map" tab. Add the following input actions (see InputEvent for details):

## 8-way movement¶

In this scenario, you want the user to press the four directional keys (up/left/down/right or W/A/S/D) and move in the selected direction. The name "8-way movement" comes from the fact that the player can move diagonally by pressing two keys at the same time.

Add a script to the character body and add the following code:

```extends CharacterBody2D

@export var speed = 400

func get_input():
var input_direction = Input.get_vector("left", "right", "up", "down")
velocity = input_direction * speed

func _physics_process(delta):
get_input()
move_and_slide()
```

In the `get_input()` function, we use Input `get_vector()` to check for the four key events and sum return a direction vector.

We can then set our velocity by multiplying this direction vector, which has a length of `1`, by our desired speed.

Tip

If you've never used vector math before, or need a refresher, you can see an explanation of vector usage in Godot at Vector math.

Note

If the code above does nothing when you press the keys, double-check that you've set up input actions correctly as described in the Setup part of this tutorial.

## Rotation + movement¶

This type of movement is sometimes called "Asteroids-style" because it resembles how that classic arcade game worked. Pressing left/right rotates the character, while up/down moves it forward or backward in whatever direction it's facing.

```extends CharacterBody2D

@export var speed = 400
@export var rotation_speed = 1.5

var rotation_direction = 0

func get_input():
rotation_direction = Input.```