減少玩家健康的陷阱是一個有趣的遊戲元素,可以通過條件語句來編碼。通過創建一個在觸碰時將玩家的健康值設置為零的部件來練習使用條件語句。
設置陷阱
陷阱在具有基於移動挑戰的遊戲中非常有效,例如障礙賽。這些步驟將從設置必要的變量和函數開始。盡量在不查看代碼框的情況下完成。
創建並命名一個陷阱部件。在部件中插入一個腳本。
在腳本中,添加一個描述性註釋,然後使用變量來引用腳本的父級。
-- 如果玩家觸碰這個部件,將他們的健康設置為 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 中是否包含 Humanoid 對象。
查找特定對象
函數 FindFirstChildWhichIsA() 可用於查找特定對象類型,這很方便,因為我們正在尋找 Humanoid 類型的對象。玩家可能只會用他們化身的一部分觸碰陷阱,因此必須設置一個變量來查找觸碰部件的父級並在其中搜索 Humanoid。
在 onTouch() 中,輸入 local character = otherPart.Parent。
local trapPart = script.Parentlocal function onTouch(otherPart)-- 查找 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 語句檢查
如果找到 Humanoid,則將 Humanoid 的健康值設置為零。
使用 if 語句檢查是否成功將 Humanoid 分配給 local humanoid。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 評估是否找到 Humanoidif humanoid thenendendtrapPart.Touched:Connect(onTouch)添加一個打印語句並檢查到目前為止的代碼。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 評估是否找到 Humanoidif humanoid thenprint("找到一個 Humanoid")endendtrapPart.Touched:Connect(onTouch)運行 代碼並檢查每當玩家觸碰該部件時是否可以看到輸出。
更改玩家的健康
如果語句為真,您可以使用相同的 humanoid 變量將玩家的健康設置為 0。
在 then 和 end 之間,輸入 humanoid.Health = 0。
完成的腳本local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 評估是否找到 Humanoidif humanoid thenprint("找到一個 Humanoid")humanoid.Health = 0endendtrapPart.Touched:Connect(onTouch)測試陷阱。
總結
這個陷阱部件使用條件語句來檢測 Humanoid 部件並將 Humanoid 的健康值設置為零。這個腳本是對之前陷阱腳本的改進,後者無論觸碰的物體是什麼都會摧毀它。
然而,它仍然有一些缺陷。Humanoid 不僅存在於玩家中。Humanoid 也存在於非可玩角色中。該腳本也僅能將玩家的健康設置為零。您可以嘗試減少少量健康,但可能會比預期更快地減少健康。後面的課程提供了進一步的改進,以更好地控制從玩家身上減少多少健康。