Brake and Drag
Lesson 3 of 20 in Coddy's Godot Game: Neon Circuit course.
Let go of Up and the car rolls on forever. Two things fix that.
Drag slows a moving car a little every frame. Take 60 percent of the velocity away each second:
velocity *= 1.0 - drag * deltaAnd Down brakes. Read Up and Down together, so the throttle goes from -1 to 1. While the car still rolls forward, Down pushes back harder than the engine pushes forward. Once it stops, Down reverses:
var throttle := Input.get_axis("move_down", "move_up")
if throttle < 0.0 and speed > 10.0:
velocity += forward * throttle * accel * 1.6 * delta
else:
velocity += forward * throttle * accel * deltaChallenge
Easy- Add
@export var drag := 0.6. - Read the throttle with
get_axisas above. - Replace the line that grows the velocity with the if and else.
- Before
limit_length, apply the drag.
Try it yourself
extends Node2D
@export var accel := 260.0
@export var max_speed := 200.0
@export var turn_speed := 3.2
var velocity := Vector2.ZERO
func _physics_process(delta: float) -> void:
var throttle := Input.get_action_strength("move_up")
var steer := Input.get_axis("move_left", "move_right")
var forward := Vector2.RIGHT.rotated(rotation)
var speed := velocity.dot(forward)
velocity += forward * throttle * accel * delta
rotation += steer * turn_speed * delta * clampf(absf(speed) / 90.0, 0.0, 1.0) * signf(speed + 0.01)
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