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()
.