The Locked Door
Part of the Projects section of Coddy's Godot journey. Lesson 31 of 36.
A Door blocks the way to the stairs. It is a StaticBody2D, so move_and_slide stops the hero at it. In front of it is DoorZone, an Area2D a little wider than the door, so the hero reaches it first.
When the hero walks into the zone with the key, the door opens:
func _on_door_zone_body_entered(body):
if has_key:
$Door.queue_free()
$DoorZone.queue_free()Remove the zone too. Otherwise the hero walks back into it, $Door no longer exists, and the game stops with Node not found.
Remove the door with queue_free(). hide() only stops the drawing. Its collision shape would still block the hero.
Challenge
MediumOpen the door with the key.
- In
main.gd, connect$DoorZone.body_enteredto a function. - When a body enters and
has_keyis true, remove$Doorand$DoorZone.
Press Play, take the key and walk to the door: it opens. Then Check.
Try it yourself
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
All lessons in Projects
1Project: Breakout
Breakout PaddleKeep the Paddle on Screen4Project: Dungeon Crawler
Walk the DungeonPick Up the KeyPractice on your own: Godot playground