Menu
CoddyTech

最佳单圈

Coddy Godot 游戏:霓虹赛道 课程的第 19 课,共 20 课。

最快圈速会让每场比赛都有一个需要超越的目标。把它保存在 static var 中:它属于脚本,而不是场景,因此重新加载场景后它仍会保留(下一课会讲到)。

static var best_lap := 0.0

每跑完一圈,如果这一圈更快(或者这是第一圈),它就会成为最快圈速:

if best_lap == 0.0 or lap_time < best_lap:
	best_lap = lap_time
challenge icon

挑战

简单

保留你的最佳圈速。

  1. 在常量下方添加 static var。
  2. 在 finish_lap 中,在圈速归零前保存最佳圈速。
  3. 在 $HUD/Best 中显示 "Best " + (clock(best_lap) if best_lap > 0.0 else "--")。
  4. 将结束消息设为 "%s\nTime %s Best lap %s" % [words, clock(race_time), clock(best_lap)]。

按“开始”并驾驶两圈:“Best”会显示你更快的那一圈。然后按“检查”。

亲手试试

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
var boost_time := 0.0
var boost_charge := 0.0
var active := true

@onready var track: Node2D = $"../Track"


func _physics_process(delta: float) -> void:
	var throttle := 0.0
	var steer := 0.0
	if active:
		throttle = Input.get_axis("move_down", "move_up")
		steer = Input.get_axis("move_left", "move_right")
		if Input.is_action_just_pressed("action") and boost_charge >= 1.0:
			boost_charge = 0.0
			boost_time = 1.0
	boost_charge = minf(1.0, boost_charge + delta / 10.0)
	$"../HUD/Boost".scale.x = boost_charge

	var forward := Vector2.RIGHT.rotated(rotation)
	var speed := velocity.dot(forward)
	var top := max_speed
	var grip_now := grip
	if boost_time > 0.0:
		boost_time -= delta
		top = max_speed * 1.3
		velocity += forward * accel * delta
	for pad in get_tree().get_nodes_in_group("boost_pads"):
		if position.distance_to(pad.position) < 22.0:
			boost_time = maxf(boost_time, 0.4)
	for oil in get_tree().get_nodes_in_group("oil"):
		if position.distance_to(oil.position) < 20.0:
			grip_now = grip * 0.12
	if not track.is_on_road(position):
		top = max_speed * 0.45
		velocity *= 1.0 - 2.5 * delta

	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_now * delta)
	velocity *= 1.0 - drag * delta
	if velocity.length() > top:
		velocity = velocity.move_toward(velocity.limit_length(top), accel * 2.0 * delta)
	position += velocity * delta
	$Exhaust.emitting = throttle > 0.0 or boost_time > 0.0
	$Flame.visible = boost_time > 0.0

Godot 游戏:霓虹赛道中的所有课

自己练习: Godot 在线编辑器