Menu
CoddyTech

通过管道得分

本课属于 Coddy Godot 学习旅程的“项目”单元。第 27 课,共 36 课。

每通过一个管道,就得 1 分。管道有一个名为 Gap 的子节点 Area2D,它是一条位于开口后方的窄带。飞行物只有穿过开口后才会碰到它,因此碰到它时就得分。

在 pipe.gd 中,通过 $Gap 连接子节点的信号,并发出 scored:

$Gap.body_entered.connect(_on_gap_body_entered)

func _on_gap_body_entered(body):
	scored.emit()

在 main.gd 中,连接每个新管道的 scored。将 score 加 1,并在 $HUD/Score 中显示它。str(score) 会将数字转换为文本。开始时显示 0。

challenge icon

挑战

中等

每通过一个管道,就得 1 分。

  1. 在 pipe.gd 中,添加 signal scored,连接 $Gap.body_entered,并在物体进入间隙时发出 scored。
  2. 在 main.gd 中,添加 var score = 0,并在开始时在 $HUD/Score 中显示 0。
  3. 将每个管道的 scored 连接到一个函数,该函数会将分数加 1 并显示分数。

按下“开始”并飞过间隙:分数会显示 1。然后点击“检查”。

亲手试试

extends Area2D

signal hit

const SPEED = 160

func _ready():
	body_entered.connect(_on_body_entered)

func _physics_process(delta):
	position.x -= SPEED * delta
	if position.x < -60:
		queue_free()

func _on_body_entered(body):
	hit.emit()

项目中的所有课

自己练习: Godot 在线编辑器