Acceleration and Velocity for 2D Character Controller

Godot Version



Hello. I’m extremely new to Godot, and while I have some experience with Unity and Unreal, much of it is working knowledge and not very helpful to me when it comes to writing code. My current project to help familiarize myself with the engine and what I am capable of (which isn’t much!) is a simple racing game.

I have several features in mind for this little game, but arguably most important is the movement, which is what brings me here. I’ve used a character controller example (here) to set up the video above. This is very close to what I’m going for, but of course it falls on me to figure out how to refine it for my own purposes.

For reference, the code is here:
And HERE is an example video of the script in engine

extends CharacterBody2D

@export var speed = 400
@export var rotation_speed = 1.5

var rotation_direction = 0

func get_input():
rotation_direction = Input.get_axis("left", "right")
velocity = transform.x * Input.get_axis("down", "up") * speed

func _physics_process(delta):
rotation += rotation_direction * rotation_speed * delta

What this character controller currently lacks is two crucial additions, which are: acceleration i.e. an input will gradually increase the player speed before maxing out, and releasing the input will gradually reduce the speed to zero (vice versa for braking), and locking rotation when the player speed is zero (making it so the player cannot endlessly spiral when not moving).

I’m mostly looking for resources and advice on how best to achieve the result I’ve outlined above, as I want to make sure I’m actually learning rather than copy & pasting the code of others more knowledgeable than I.

Look into basic physics.

Velocity is a change of position over time.

Acceleration is a change of velocity over time.

Accelerations are caused by a forces.

Friction is force that creates a deceleration. Or a negative acceleration.

All forces can be represented by one formula.

F = MA, Force = Mass • Acceleration.

Rigid bodies will use these mechanics

But for character controllers you can u can use the move_towards() function with the velocity vector2 property to simulate accelerations. Also Vector2.lerp() is an alternative function to do the same thing.

Locking rotations can be done by checking the state of the velocity with an if statement.

if velocity != Vector2.ZERO: 
  # rotate