Level 2 - Key Hunt Challenge
Key Objectives
Prerequisites


Professor
Ready to level up your game development skills? Today we'll combine what you learned about doors with new concepts like player tracking and event handling. Let's create an exciting key hunt challenge!
Step-by-Step Guide
Step 1: Creating the Key and Obstacles
Create the Key
Create Obstacles
Step 2: Scripting the Key Hunt
Professor
Now for the exciting part - let's add the code that makes our key collectible and our door check for it!
Key Collection Script
Door Lock Script
1local key = script.Parent
2
3local function onTouched(hit)
4 local player = game.Players:GetPlayerFromCharacter(hit.Parent)
5 if player then
6 -- Set HasKey variable for the player
7 player.HasKey = true
8 -- Play collection effect
9 local effect = Instance.new("Explosion")
10 effect.Position = key.Position
11 effect.BlastPressure = 0
12 effect.BlastRadius = 0
13 effect.Parent = game.Workspace
14 -- Remove the key
15 key:Destroy()
16 end
17end
18
19key.Touched:Connect(onTouched)
1local door = script.Parent
2local TweenService = game:GetService("TweenService")
3local isOpen = false
4
5local function onTouched(hit)
6 local player = game.Players:GetPlayerFromCharacter(hit.Parent)
7 if player and player.HasKey then
8 if not isOpen then
9 isOpen = true
10 -- Door opening animation
11 local tweenInfo = TweenInfo.new(1, Enum.EasingStyle.Quad)
12 local tween = TweenService:Create(door, tweenInfo, {
13 CFrame = door.CFrame * CFrame.Angles(0, math.rad(90), 0)
14 })
15 tween:Play()
16 -- Play success sound
17 local sound = Instance.new("Sound")
18 sound.SoundId = "rbxassetid://YOURSOUNDID"
19 sound.Parent = door
20 sound:Play()
21 end
22 else
23 -- Play locked sound
24 local lockedSound = Instance.new("Sound")
25 lockedSound.SoundId = "rbxassetid://YOURSOUNDID"
26 lockedSound.Parent = door
27 lockedSound:Play()
28 end
29end
30
31door.Touched:Connect(onTouched)
Step 3: Testing Your Game
Professor
Time to test everything! Make sure the key collection works and the door only opens for players with the key.
Test the Challenge
Congratulations! 🎉
Test your knowledge
Quiz Challenge
Test your knowledge with 3 questions!
What's Next?
Ready for more advanced game mechanics? Continue to Level 3 where we'll learn about creating power-ups and special effects!
Additional Resources
Key Concepts Explained
Touched Events
Touched events fire when one part comes into contact with another. They're perfect for detecting when players interact with objects in your game.
Player Variables
Variables stored in the player object persist throughout their session, making them ideal for tracking things like collected items or game progress.
Conditional Statements
If statements allow your code to make decisions based on conditions, like checking whether a player has collected a key before opening a door.