減少玩家健康值的陷阱是一個有趣的遊戲元素,可以通過條件語句進行編碼。通過創建一個在接觸時將玩家的健康值設置為零的部件來練習使用條件語句。
設置陷阱
陷阱在進行基於移動挑戰的體驗中極為有效,例如障礙賽。這些步驟將從設置必要的變量和函數開始。在查看代碼框之前,盡量自己完成。
創建並命名一個陷阱部件。在部件中插入一個腳本。
在腳本中,添加一個描述性註釋,然後使用變量來引用腳本的父對象。
-- 如果玩家觸碰此部件,則將其健康值設置為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。該腳本也僅適合將玩家的健康值設置為零。您可以嘗試減少少量健康值,但可能會比預期更快地減少健康值。後面的課程將提供進一步的改進,以便更好地控制從玩家身上扣除的健康值。