Stay on the Road
Lesson 5 of 20 in Coddy's Godot Game: Neon Circuit course.
The track is drawn by track.gd, which also answers questions about it. track.is_on_road(position) is true while a point is on the road. Off it, the car should crawl through the grass.
Get the track node once, when the car is ready:
@onready var track: Node2D = $"../Track"Then keep a top speed for this frame. Off the road it is 45 percent of max_speed, and the grass slows the car too:
var top := max_speed
if not track.is_on_road(position):
top = max_speed * 0.45
velocity *= 1.0 - 2.5 * deltaLast, replace limit_length. Snapping the speed down would stop the car dead at the road's edge, so ease it down to the top speed:
if velocity.length() > top:
velocity = velocity.move_toward(velocity.limit_length(top), accel * 2.0 * delta)Challenge
Easy- Add the
@onreadyline for the track. - After
speed, work outtopand the off road slowdown. - Replace the
limit_lengthline with the two lines above. - Press Play and drive onto the grass.
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
@export var grip := 7.0
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)
var side := forward.orthogonal()
velocity -= side * velocity.dot(side) * minf(1.0, grip * delta)
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