Resta in pista
Lezione 5 di 20 del corso Gioco Godot: Circuito al neon di Coddy.
Il tracciato è disegnato da track.gd, che risponde anche alle domande su di esso. track.is_on_road(position) è true quando un punto si trova sulla strada. Fuori strada, l’auto dovrebbe avanzare lentamente sull’erba.
Ottieni il nodo del tracciato una volta, quando l’auto è pronta:
@onready var track: Node2D = $"../Track"Quindi imposta una velocità massima per questo frame. Fuori strada è il 45 percento di max_speed e l’erba rallenta anche l’auto:
var top := max_speed
if not track.is_on_road(position):
top = max_speed * 0.45
velocity *= 1.0 - 2.5 * deltaInfine, sostituisci limit_length. Ridurre bruscamente la velocità fermerebbe l’auto di colpo al bordo della strada, quindi rallentala gradualmente fino alla velocità massima:
if velocity.length() > top:
velocity = velocity.move_toward(velocity.limit_length(top), accel * 2.0 * delta)Sfida
Facile- Aggiungi la riga
@onreadyper la pista. - Dopo
speed, calcolatope il rallentamento fuori pista. - Sostituisci la riga
limit_lengthcon le due righe precedenti. - Premi «Gioca» e guida sull'erba.
Provalo tu
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
Tutte le lezioni di Gioco Godot: Circuito al neon
Esercitati da solo: Playground Godot