Menu
CoddyTech

上锁的门

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

Door 会挡住通往楼梯的路。它是一个 StaticBody2D,所以 move_and_slide 会让英雄停在它面前。它前面是 DoorZone,这是一个比门稍宽的 Area2D,因此英雄会先到达这里。

英雄带着钥匙走进区域时,门就会打开:

func _on_door_zone_body_entered(body):
	if has_key:
		$Door.queue_free()
		$DoorZone.queue_free()

也要移除区域。否则英雄走回区域时,$Door 已经不存在,游戏就会因 Node not found 而停止。

使用 queue_free() 移除门。hide() 只会停止绘制。门的碰撞形状仍会挡住英雄。

challenge icon

挑战

中等

用钥匙打开门。

  1. 在 main.gd 中,将 $DoorZone.body_entered 连接到一个函数。
  2. 当一个物体进入且 has_key 为 true 时,移除 $Door 和 $DoorZone。

按“开始”,拿起钥匙并走到门边:门会打开。然后点击“检查”。

亲手试试

extends Node2D

var has_key = false

func _ready():
	$Key.body_entered.connect(_on_key_body_entered)

func _on_key_body_entered(body):
	has_key = true
	$Key.queue_free()
	$HUD/KeyIcon.visible = true

项目中的所有课

自己练习: Godot 在线编辑器