降低玩家生命值的陷阱是可以用條件聲明編寫的有趣遊戲元素。練習使用條件,通過創建一個部分來設置玩家的健康為零,當觸碰時。
設置陷阱
陷阱在使用基於運動的挑戰的體驗中表現得非常好,例如障礙賽。這些步驟將由設置必要的變量和功能開始。先不要看代碼盒,盡可能地進行操作。
創建並命名陷阱零件。將腳本插入零件中。
在腳指令碼中,添加說明性評論,然後使用變量來引用腳指令碼的父元素。
-- 如果玩家觸碰此部分,將他們的生命值設為 0local trapPart = script.Parent創建名為 onTouch() 的函數,並將參數命名為 otherPart 。
-- 如果玩家觸碰此部分,將他們的生命值設為 0local trapPart = script.Parentlocal function onTouch(otherPart)end將功能連接到陷阱部分的 Touched 事件,每當有東西觸碰零件時運行。
local trapPart = script.Parentlocal function onTouch(otherPart)endtrapPart.Touched:Connect(onTouch)
檢查玩家是否觸碰
記住,參數 otherPart 記錄任何觸碰陷阱部分的東西,這可能是玩家的一部分或只是底盤。
為了確保陷阱只會摧毀玩家並不會摧毀隨機裝飾物品,請使用 if/then 聲明來檢查 otherPart 中是否包含人形物物件。
尋找特定對物件
功能 FindFirstChildWhichIsA() 可以用來尋找特定對象類型,這很方便,因為我們正在尋找人形類型對物件。玩家通常只會用他們的虛擬人偶的一部分觸碰陷阱,因此必須設置變數來找到觸碰部分的父輩,並尋找 Humanoid。
在 onTouch() 中,輸入 local character = otherPart.Parent。
local trapPart = script.Parentlocal function onTouch(otherPart)-- 尋找其他零件的父對物件local character = otherPart.ParentendtrapPart.Touched:Connect(onTouch)查看 character 是否有 Humanoid 輸入:
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")endtrapPart.Touched:Connect(onTouch)
使用 if 語句檢查
如果找到人形怪物,則將人形怪物的健康設為零。
使用 if 語句來檢查是否成功將 Humanoid 指派到 local humanoid 。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 評估是否找到了人形怪物if humanoid thenendendtrapPart.Touched:Connect(onTouch)添加印刷聲明並檢查目前的代碼。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 評估是否找到了人形怪物if humanoid thenprint("Found a Humanoid")endendtrapPart.Touched:Connect(onTouch)執行 代碼,並檢查您是否能夠在玩家觸碰零件時看到輸出。
變更玩家的生命值
如果聲明是真實的,您可以使用相同的人形變量將玩家的健康設置為 0。
在 then 和 end 之間,輸入 humanoid.Health = 0 。
已完成的腳指令碼local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 評估是否找到了人形怪物if humanoid thenprint("Found a Humanoid")humanoid.Health = 0endendtrapPart.Touched:Connect(onTouch)測試罩。
總結
這個陷阱部分使用條件來偵測人形零件,並將人形的健康設為零。這個腳本是以前的陷阱指令碼的改進版,無論是什麼,都會毀滅任何接觸對象。
然而,它仍有一些缺陷。人形怪物不只在玩家身上。非玩家角色中也找到了人形怪物。腳本也只能將玩家的健康設置為零。您可以實驗減少少量生命值,但可能會比預期更快地減少生命值。之後的課程提供進一步的改進,以提供對玩家的生命值減少的更大控制。