Skip to main content

Basic Top-Down Movement

Godotโ€™s documentation already has a good example of how to do this. Not much to refine here.

This assumes that there are four inputs already defined as โ€œleftโ€, โ€œrightโ€, โ€œupโ€, and โ€œdownโ€. It will work with both keyboard and controller inputs.

The result of this will be a character that doesnโ€™t have any โ€œweightโ€. That is, they move exactly as much as the input specifies. When no input is provided, the character instantly stops. This would be fine for lofi, 8- and 16-bit games, but not suitable for anything with mass. For that, youโ€™d want some sort of acceleration, such as a basic linear acceleration.

The Codeโ€‹

extends CharacterBody2D

## The maximum speed allowed, in pixels per second
@export var max_speed: float = 200.0

func _physics_process(_delta: float) -> void:
velocity = _direction() * max_speed
move_and_slide()

func _direction() -> Vector2:
return Input.get_vector("left", "right", "up", "down")

Implementation Notesโ€‹

  • _physics_process(float) is used over _process(float) since this involves moving the character, and physics operations should be applied within the physics thread.
  • I moved Input.get_vector()โ€™s usage into a helper function because I can never remember which direction is which, but it doesnโ€™t save anything here.
  • move_and_slide() takes into account delta time, and so your character will move at a consistent rate (even if your physics frames donโ€™t)
  • This character will always move at top speed when using a keyboard for input. Using a controller, itโ€™s possible to move at less than maximum speed by not moving the joystick all the way to one direction. This could be addressed by normalizing the output of Input.get_vector().