Grip and Drift
Lesson 4 of 20 in Coddy's Godot Game: Neon Circuit course.
Turn hard and the car slides like a hockey puck: it points one way and moves another. Tyres stop that. They let a car roll forward, but not sideways.
forward.orthogonal() points to the car's side. Split the velocity into the part along it and take most of that part away each frame:
var side := forward.orthogonal()
velocity -= side * velocity.dot(side) * minf(1.0, grip * delta)With grip at 7 the car follows its nose a moment after a turn, with a short drift. Lower grip, longer drift. minf(1.0, ...) makes sure a frame never takes away more than the whole sideways part.
Challenge
Easy- Add
@export var grip := 7.0. - After the turn, take away the sideways velocity as above.
- Press Play and take a corner. Try a grip of 2 in the Inspector to drift.
Try it yourself
extends Node2D
@export var accel := 260.0
@export var max_speed := 200.0
@export var turn_speed := 3.2
@export var drag := 0.6
var velocity := Vector2.ZERO
func _physics_process(delta: float) -> void:
var throttle := Input.get_axis("move_down", "move_up")
var steer := Input.get_axis("move_left", "move_right")
var forward := Vector2.RIGHT.rotated(rotation)
var speed := velocity.dot(forward)
if throttle < 0.0 and speed > 10.0:
velocity += forward * throttle * accel * 1.6 * delta
else:
velocity += forward * throttle * accel * delta
rotation += steer * turn_speed * delta * clampf(absf(speed) / 90.0, 0.0, 1.0) * signf(speed + 0.01)
velocity *= 1.0 - drag * delta
velocity = velocity.limit_length(max_speed)
position += velocity * delta
$Exhaust.emitting = throttle > 0.0
All lessons in Godot Game: Neon Circuit
Practice on your own: Godot playground