當要監測物件與物件之間碰撞時, 就可以用到
物件.Touched:connect( (function(另外一個物件)
...
end)
|
或者
function function名字 ( 另一個物件)
...
end
物件.Touched:connect(function名字)
|
例子[]
刪除另一個物品的Script[]
例如監測物件b碰到物件a時, 物件b就會自動刪除
- 當這一個Script在物件a內
script.Parent.Touched:connect(function(otherpart)
otherpart:destroy() -- 刪除
end)
|
Kill script[]
當某一個玩家碰到這一個 Part 時,就會死亡
script.Parent.Touched:connect(function(otherpart)
Humanoid = otherpart.Parent:FindFirstChild("Humanoid") -- 找出碰到的 Part 是不是玩家
if Humanoid then
Humanoid.Health = 0 --殺死
end
end)
|
Debounce 不接受[]
觸碰Part時會多次進行,因此我們需要Debounce保證Script不會重複進行 例:
script.Parent.Touched:connect(function(otherpart)
Humanoid = otherpart.Parent:FindFirstChild("Humanoid") -- 找出碰到的 Part 是不是玩家
if Humanoid then
Humanoid.Health = Humanoid.Health + 5 --加血
wait(5) -- 以為可以限制加血間隔
end
end)
|
因為 Touch Event 是可以重複進行,因此 wait(5)並不能限制間隔 |
local debounce = false --不是進行中
script.Parent.Touched:connect(function(otherpart)
if debounce == false then --Check Event是不是在進行
debounce = true --Function 進行中
Humanoid = otherpart.Parent:FindFirstChild("Humanoid") -- 找出碰到的 Part 是不是玩家
if Humanoid then
Humanoid.Health = Humanoid.Health + 5 --加血
wait(5) -- 限制加血間隔
debounce = false --Function 完結
end
end
end)
|
Touch Event 雖然可以重複進行,但會檢查Variable (Debounce)是或否,因此可以限制Event進行次數 |
小遊戲[]
1. 你現在是路博士鐵路的顧問, 其要求你編寫一個列車安全系統(Fixed Block), 當列車駛經時就會將該路段封閉,防止兩架列車相撞。
你現在只編寫B區
- 當列車到達 B1 時, 就會將B區封鎖
- 當列車完全離開B2時, 就會將B區解鎖
- 當另外一架列車到達B1時就將其停止(已有function stop(Part名字)), 等候區域再次開放, 使用已有 function start(Part名字)今列車可繼續運行
列車有以下特微
- 列車前面有一個Part叫 "Front"
- 列車後面有一個Part叫 "Back"
物件攔 |
答案 |
---|
local occupy = false --知道區域是否關閉
script.Parent.B1.Touched:Connect(function(otherpart)
if otherpart.Name == "Front" then
if occupy == false then --檢查是否新列車
occupy = true --關閉該區域
else
stop(otherpart) --停止列車
while occupy do -- 等候區域再次開放
wait()
end
start(otherpart)
occupy = true -- 此列車繼續運行, 區域再次關閉
end
end
end)
script.Parent.B2.Touched:Connect(function(otherpart)
if otherpart.Name == "Back" then
occupy = false
end
end)
|