Asteroids-Style Movement
Asteroids-style movement is also known as โrotation + movementโ. Left and right controls the characterโs rotation, and up and down control acceleration in the direction being held.
Basic Implementationโ
This is based on the example from the Godot documentation
extends CharacterBody2D
## Rotation speed in radians per second
@export var rotation_speed: float = PI / 1.5
## Linear acceleration in pixels per second squared.
@export var acceleration: float = 300.0
func _physics_process(delta: float) -> void:
var rotation_direction: float = Input.get_axis("left", "right")
var forward_direction: float = Input.get_axis("down", "up")
rotation += rotation_direction * rotation_speed * delta
velocity += transform.x * forward_direction * _adjusted_acceleration(delta)
func _adjusted_acceleration(delta: float) -> float:
return acceleration * delta
Why use transform.x
? This value always represents the right-hand side of
the node, regardless of rotation. If your character scene is set up so that the
characterโs โfrontโ is facing to the right, this will work great.
For more details on this, read the following guides, both from the Godot documentation:
This is all driven off of the Transform2D class.
a vector pointing in the bodyโs โforwardโ direction
โ Godot documentation
Linear Accelerationโ
This feels much closer to the actual Asteroids game. Velocity is maintained when thereโs no input.
The approach to linear velocity is similar to the 8-way movement implementation.
extends CharacterBody2D
## Rotation speed in radians per second
@export var rotation_speed: float = PI / 1.5
## Linear acceleration in pixels per second squared.
@export var acceleration: float = 300.0
func _physics_process(delta: float) -> void:
var rotation_direction: float = Input.get_axis("left", "right")
var forward_direction: float = Input.get_axis("down", "up")
rotation += rotation_direction * rotation_speed * delta
velocity += transform.x * forward_direction * _adjusted_acceleration(delta)
func _adjusted_acceleration(delta: float) -> float:
return acceleration * delta