如果/則陷阱練習

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

減少玩家健康值的陷阱是一個有趣的遊戲元素,可以通過條件語句進行編碼。通過創建一個在接觸時將玩家的健康值設置為零的部件來練習使用條件語句。

設置陷阱

陷阱在進行基於移動挑戰的體驗中極為有效,例如障礙賽。這些步驟將從設置必要的變量和函數開始。在查看代碼框之前,盡量自己完成。

  1. 創建並命名一個陷阱部件。在部件中插入一個腳本。

  2. 在腳本中,添加一個描述性註釋,然後使用變量來引用腳本的父對象。


    -- 如果玩家觸碰此部件,則將其健康值設置為0
    local trapPart = script.Parent
  3. 創建一個名為 onTouch() 的函數,並使用參數 otherPart


    -- 如果玩家觸碰此部件,則將其健康值設置為0
    local trapPart = script.Parent
    local function onTouch(otherPart)
    end
  4. 將該函數連接到陷阱部件的 Touched 事件,以便每當有物體觸碰該部件時運行。


    local trapPart = script.Parent
    local function onTouch(otherPart)
    end
    trapPart.Touched:Connect(onTouch)

檢查玩家觸碰

請記住,參數 otherPart 記錄了觸碰陷阱部件的任何物體,這可能是玩家的一部分或僅僅是基板。

為了確保陷阱只會消滅玩家,而不會消滅隨機的裝飾物體,請使用 if/then 語句來檢查 otherPart 中是否包含 Humanoid 對象。

查找特定對象

函數 FindFirstChildWhichIsA() 可用於查找特定類型的對象,這很方便,因為我們正在尋找 Humanoid 類型的對象。玩家可能會用他們化身的一部分觸碰陷阱,因此必須設置一個變量來查找觸碰部件的父對象並搜索其 Humanoid。

  1. onTouch() 中,輸入 local character = otherPart.Parent


    local trapPart = script.Parent
    local function onTouch(otherPart)
    -- 查找 otherPart 的父對象
    local character = otherPart.Parent
    end
    trapPart.Touched:Connect(onTouch)
  2. 輸入以下代碼來檢查 character 是否具有 Humanoid

    local humanoid = character:FindFirstChildWhichIsA("Humanoid")


    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    end
    trapPart.Touched:Connect(onTouch)

使用 if 語句檢查

如果找到一個 Humanoid,則將 Humanoid 的健康值設置為零。

  1. 使用 if 語句檢查是否成功將 Humanoid 分配給 local humanoid


    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 評估是否找到了 Humanoid
    if humanoid then
    end
    end
    trapPart.Touched:Connect(onTouch)
  2. 添加一個打印語句並檢查目前的代碼。


    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 評估是否找到了 Humanoid
    if humanoid then
    print("找到了 Humanoid")
    end
    end
    trapPart.Touched:Connect(onTouch)
  3. 運行 代碼並檢查每當玩家觸碰部件時是否可以看到輸出。

改變玩家的健康值

如果語句為真,您可以使用相同的 humanoid 變量將玩家的健康值設置為 0。

  1. thenend 之間,輸入 humanoid.Health = 0

    完成的腳本

    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 評估是否找到了 Humanoid
    if humanoid then
    print("找到了 Humanoid")
    humanoid.Health = 0
    end
    end
    trapPart.Touched:Connect(onTouch)
  2. 測試陷阱。

總結

這個陷阱部件使用條件語句來檢測 Humanoid 部件並將 Humanoid 的健康值設置為零。這個腳本改進了先前的陷阱腳本,該腳本會銷毀任何接觸的物體,不論是什麼。

不過,它仍然有一些缺陷。Humanoid 不僅存在於玩家中。在非可玩角色中也可以找到 Humanoid。該腳本也僅適合將玩家的健康值設置為零。您可以嘗試減少少量健康值,但可能會比預期更快地減少健康值。後面的課程將提供進一步的改進,以便更好地控制從玩家身上扣除的健康值。

©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。