2D movement overview

    We’ll use 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 with two children: Sprite and CollisionShape2D. You can use the Godot icon (“icon.png”) for the Sprite’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):

    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 kinematic body and add the following code:

    GDScript

    C#

    1. using Godot;
    2. using System;
    3. public class Movement : KinematicBody2D
    4. {
    5. [Export] public int Speed = 200;
    6. Vector2 velocity = new Vector2();
    7. public void GetInput()
    8. {
    9. velocity = new Vector2();
    10. if (Input.IsActionPressed("right"))
    11. velocity.x += 1;
    12. if (Input.IsActionPressed("left"))
    13. velocity.x -= 1;
    14. if (Input.IsActionPressed("down"))
    15. velocity.y += 1;
    16. if (Input.IsActionPressed("up"))
    17. velocity.y -= 1;
    18. velocity = velocity.Normalized() * Speed;
    19. }
    20. public override void _PhysicsProcess(float delta)
    21. {
    22. GetInput();
    23. velocity = MoveAndSlide(velocity);
    24. }
    25. }

    In the get_input() function we check for the four key events and sum them up to get the velocity vector. This has the benefit of making two opposite keys cancel each other out, but will also result in diagonal movement being faster due to the two directions being added together.

    We can prevent that if we normalize the velocity, which means we set its length to 1, and multiply by the desired speed.

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

    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.

    GDScript

    C#

    1. extends KinematicBody2D
    2. export (int) var speed = 200
    3. export (float) var rotation_speed = 1.5
    4. var rotation_dir = 0
    5. func get_input():
    6. rotation_dir = 0
    7. velocity = Vector2()
    8. if Input.is_action_pressed('right'):
    9. rotation_dir += 1
    10. if Input.is_action_pressed('left'):
    11. rotation_dir -= 1
    12. if Input.is_action_pressed('down'):
    13. velocity = Vector2(-speed, 0).rotated(rotation)
    14. if Input.is_action_pressed('up'):
    15. velocity = Vector2(speed, 0).rotated(rotation)
    16. func _physics_process(delta):
    17. get_input()
    18. rotation += rotation_dir * rotation_speed * delta
    19. velocity = move_and_slide(velocity)

    Here we’ve added two new variables to track our rotation direction and speed. Again, pressing both keys at once will cancel out and result in no rotation. The rotation is applied directly to the body’s rotation property.

    To set the velocity, we use the Vector2.rotated() method, so that it points in the same direction as the body. rotated() is a useful vector function that you can use in many circumstances where you would otherwise need to apply trigonometric functions.

    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

    GDScript

    C#

    1. extends KinematicBody2D
    2. export (int) var speed = 200
    3. var velocity = Vector2()
    4. func get_input():
    5. look_at(get_global_mouse_position())
    6. velocity = Vector2()
    7. if Input.is_action_pressed('down'):
    8. velocity = Vector2(-speed, 0).rotated(rotation)
    9. if Input.is_action_pressed('up'):
    10. velocity = Vector2(speed, 0).rotated(rotation)
    11. func _physics_process(delta):
    12. get_input()
    13. velocity = move_and_slide(velocity)
    1. using Godot;
    2. using System;
    3. {
    4. [Export] public int Speed = 200;
    5. Vector2 velocity = new Vector2();
    6. public void GetInput()
    7. {
    8. LookAt(GetGlobalMousePosition());
    9. velocity = new Vector2();
    10. if (Input.IsActionPressed("down"))
    11. velocity = new Vector2(-Speed, 0).Rotated(Rotation);
    12. if (Input.IsActionPressed("up"))
    13. velocity = new Vector2(Speed, 0).Rotated(Rotation);
    14. velocity = velocity.Normalized() * Speed;
    15. }
    16. public override void _PhysicsProcess(float delta)
    17. {
    18. GetInput();
    19. velocity = MoveAndSlide(velocity);
    20. }
    21. }

    GDScript

    C#

    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.

    GDScript

    C#

    1. extends KinematicBody2D
    2. export (int) var speed = 200
    3. var target = Vector2()
    4. var velocity = Vector2()
    5. func _input(event):
    6. if event.is_action_pressed('click'):
    7. target = get_global_mouse_position()
    8. func _physics_process(delta):
    9. velocity = (target - position).normalized() * speed
    10. # rotation = velocity.angle()
    11. if (target - position).length() > 5:
    12. velocity = move_and_slide(velocity)

    Note the length() 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 rotation 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.

    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.