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):

../../_images/movement_inputs.webp

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.

../../_images/movement_8way.gif

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

GDScriptC#

  1. extends CharacterBody2D
  2. @export var speed = 400
  3. func get_input():
  4. var input_direction = Input.get_vector("left", "right", "up", "down")
  5. velocity = input_direction * speed
  6. func _physics_process(delta):
  7. get_input()
  8. move_and_slide()
  1. using Godot;
  2. public partial class Movement : CharacterBody2D
  3. {
  4. [Export]
  5. public int Speed { get; set; } = 400;
  6. public void GetInput()
  7. {
  8. Vector2 inputDirection = Input.GetVector("left", "right", "up", "down");
  9. Velocity = inputDirection * Speed;
  10. }
  11. public override void _PhysicsProcess(double delta)
  12. {
  13. GetInput();
  14. MoveAndSlide();
  15. }
  16. }

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.

../../_images/movement_rotate1.gif

GDScriptC#

  1. extends CharacterBody2D
  2. @export var speed = 400
  3. @export var rotation_speed = 1.5
  4. var rotation_direction = 0
  5. func get_input():
  6. rotation_direction = Input.get_axis("left", "right")
  7. velocity = transform.x * Input.get_axis("down", "up") * speed
  8. func _physics_process(delta):
  9. get_input()
  10. rotation += rotation_direction * rotation_speed * delta
  11. move_and_slide()
  1. using Godot;
  2. public partial class Movement : CharacterBody2D
  3. {
  4. [Export]
  5. public int Speed { get; set; } = 400;
  6. [Export]
  7. public float RotationSpeed { get; set; } = 1.5f;
  8. private float _rotationDirection;
  9. public void GetInput()
  10. {
  11. _rotationDirection = Input.GetAxis("left", "right");
  12. Velocity = Transform.X * Input.GetAxis("down", "up") * Speed;
  13. }
  14. public override void _PhysicsProcess(double delta)
  15. {
  16. GetInput();
  17. Rotation += _rotationDirection * RotationSpeed * (float)delta;
  18. MoveAndSlide();
  19. }
  20. }

Here we’ve added two variables to track our rotation direction and speed. The rotation is applied directly to the body’s rotation property.

To set the velocity, we use the body’s transform.x which is a vector pointing in the body’s “forward” direction, and multiply that by the speed.

Rotation + movement (mouse)

This style of movement is a variation of the previous one. This time, the direction is set by the mouse position instead of the keyboard. The character will always “look at” the mouse pointer. The forward/back inputs remain the same, however.

../../_images/movement_rotate2.gif

GDScriptC#

  1. extends CharacterBody2D
  2. @export var speed = 400
  3. func get_input():
  4. look_at(get_global_mouse_position())
  5. velocity = transform.x * Input.get_axis("down", "up") * speed
  6. func _physics_process(delta):
  7. get_input()
  8. move_and_slide()
  1. using Godot;
  2. public partial class Movement : CharacterBody2D
  3. {
  4. [Export]
  5. public int Speed { get; set; } = 400;
  6. public void GetInput()
  7. {
  8. LookAt(GetGlobalMousePosition());
  9. Velocity = Transform.X * Input.GetAxis("down", "up") * Speed;
  10. }
  11. public override void _PhysicsProcess(double delta)
  12. {
  13. GetInput();
  14. MoveAndSlide();
  15. }
  16. }

Here we’re using the Node2D look_at() method to point the player towards the mouse’s position. Without this function, you could get the same effect by setting the angle like this:

GDScriptC#

  1. rotation = get_global_mouse_position().angle_to_point(position)
  1. var rotation = GetGlobalMousePosition().AngleToPoint(Position);

Click-and-move

This last example uses only the mouse to control the character. Clicking on the screen will cause the player to move to the target location.

../../_images/movement_click.gif

GDScriptC#

  1. extends CharacterBody2D
  2. @export var speed = 400
  3. var target = position
  4. func _input(event):
  5. if event.is_action_pressed("click"):
  6. target = get_global_mouse_position()
  7. func _physics_process(delta):
  8. velocity = position.direction_to(target) * speed
  9. # look_at(target)
  10. if position.distance_to(target) > 10:
  11. move_and_slide()
  1. using Godot;
  2. public partial class Movement : CharacterBody2D
  3. {
  4. [Export]
  5. public int Speed { get; set; } = 400;
  6. private Vector2 _target;
  7. public override void _Input(InputEvent @event)
  8. {
  9. if (@event.IsActionPressed("click"))
  10. {
  11. _target = GetGlobalMousePosition();
  12. }
  13. }
  14. public override void _PhysicsProcess(double delta)
  15. {
  16. Velocity = Position.DirectionTo(_target) * Speed;
  17. // LookAt(target);
  18. if (Position.DistanceTo(_target) > 10)
  19. {
  20. MoveAndSlide();
  21. }
  22. }
  23. }

Note the distance_to() check we make prior to movement. Without this test, the body would “jitter” upon reaching the target position, as it moves slightly past the position and tries to move back, only to move too far and repeat.

Uncommenting the look_at() line will also turn the body to point in its direction of motion if you prefer.

Tip

This technique can also be used as the basis of a “following” character. The target position can be that of any object you want to move to.

Summary

You may find these code samples useful as starting points for your own projects. Feel free to use them and experiment with them to see what you can make.

You can download this sample project here: 2d_movement_starter.zip

Previous Next


© Copyright 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision 53e837c6.

Built with Sphinx using a theme provided by Read the Docs.