Lập trình Roblox · Khóa 2: Lập trình Luau cơ bản – Obby
| Scratch | Roblox |
|---|---|
| khi nhân vật này được bấm | ClickDetector.MouseClick |
| khi phím E được bấm (gần nhân vật) | ProximityPrompt.Triggered |
local nut = script.Parent local click = nut.ClickDetector click.MouseClick:Connect(function(player) print(player.Name .. " đã bấm nút") workspace.Den.BrickColor = BrickColor.random() end)
MouseClick gửi kèm player – người đã bấmlocal ruong = script.Parent local prompt = ruong.ProximityPrompt prompt.Triggered:Connect(function(player) print(player.Name .. " mở rương!") ruong.Color = Color3.fromRGB(255, 215, 0) prompt.Enabled = false -- chỉ mở được một lần end)
local TweenService = game:GetService("TweenService") local cua = script.Parent local prompt = cua.ProximityPrompt local viTriDong = cua.Position local viTriMo = cua.Position + Vector3.new(0, 10, 0) local dangMo = false prompt.Triggered:Connect(function(player) dangMo = not dangMo -- đảo trạng thái local dich = viTriDong if dangMo then dich = viTriMo prompt.ActionText = "Đóng cửa" else prompt.ActionText = "Mở cửa" end TweenService:Create(cua, TweenInfo.new(1), {Position = dich}):Play() end)
player:SetAttribute("CoChiaKhoa", true) – ghiplayer:GetAttribute("CoChiaKhoa") – đọc (chưa ghi thì là nil)Script trong khối ChiaKhoa:
local Players = game:GetService("Players") local chiaKhoa = script.Parent chiaKhoa.Touched:Connect(function(hit) local player = Players:GetPlayerFromCharacter(hit.Parent) if player and not player:GetAttribute("CoChiaKhoa") then player:SetAttribute("CoChiaKhoa", true) print(player.Name .. " nhặt được chìa khóa!") end end)
local cua = script.Parent local prompt = cua.ProximityPrompt prompt.Triggered:Connect(function(player) if player:GetAttribute("CoChiaKhoa") then cua.Transparency = 0.8 cua.CanCollide = false prompt.Enabled = false else print(player.Name .. " cần tìm chìa khóa trước!") end end)
Rương có ProximityPrompt "Mở rương", giữ phím E 2 giây mới mở. Mở xong rương phát sáng (Material Neon) và có Sparkles.
Cửa mở khi bấm E, tự đóng lại sau 5 giây.
Màn chơi có 3 chìa khóa (Đỏ, Xanh, Vàng). Cửa cuối chỉ mở khi người chơi có đủ 3 chìa.
| Em gặp | Nguyên nhân |
|---|---|
| Không hiện lời nhắc | ProximityPrompt không nằm trong Part, hoặc Enabled tắt |
| Bấm chuột không có gì | thiếu ClickDetector trong Part |
GetAttribute luôn nil | gõ sai tên attribute (phân biệt hoa thường) |
| Cửa giật lên xuống | bấm nhiều lần khi Tween chưa xong – thêm debounce |
dangMo = not dangMo để đóng / mởSetAttribute / GetAttribute – thông tin riêng từng người chơi