評估多個陳述

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

如果陳述需要在執行代碼之前滿足多個條件,則可以使用 if 陳述。關鍵字 and 允許您將陳述結合在一起。以下代碼首先評估兩加兩是否等於六,然後評估四是否不等於六。如果兩個陳述都為真,則代碼將執行。

-- 不會執行
if 2 + 2 == 6 and 4 ~= 6 then
print("兩個陳述都為真")
end
-- 會執行
if 4 + 2 == 6 and 4 ~= 6 then
print("兩個陳述都為真")
end

創建一個增益道具

增益道具是遊戲內的物品,可以給玩家特殊的能力,例如飛行、隱形或加速。這個增益道具將在每次觸碰增益道具時提升玩家的行走速度。持續施加增益可能會使玩家速度過快,因此將使用 and 來控制行走速度的上限。

設置增益道具

使用這段代碼與一個簡單的部件或模型,例如水晶、硬幣或發光的霓虹球。

  1. 創建一個名為 Powerup 的新部件,並插入一個名為 WalkSpeedManager 的腳本。

  2. 宣告一個名為 speedBoost 的變數,並將其分配給腳本的父對象。

    -- 觸碰時給予暫時的速度增益
    local speedBoost = script.Parent
  3. 設置一個名為 onTouch 的函數,並將其連接到父對象的 Touched 事件。然後進行遊玩測試並檢查您的工作。

    local speedBoost = script.Parent
    local function onTouch(otherPart)
    print("某物觸碰了 speedBoost")
    end
    speedBoost.Touched:Connect(onTouch)
  4. WalkSpeed 屬性位於 Humanoid 對象上。使用創建陷阱部件時使用的相同模式,創建一個條件來檢查 Humanoid 對象。

    尋找 Humanoid 部件
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid then
    print("找到了 Humanoid")
    end
    end

加速玩家

每次觸碰增益道具時,速度增益將使角色行走得更快。這將迅速變得非常非常快。關鍵字 and 將確保玩家不會過快,只有在玩家的速度低於某個值時才啟用速度增益。

  1. 如果找到 Humanoid,則取當前的 WalkSpeed 值並加 10。進行遊玩測試,您的角色每次觸碰速度增益時都會變得更快。

    增加當前 WalkSpeed
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid then
    humanoid.WalkSpeed += 10
    end
    end
    speedBoost.Touched:Connect(onTouch)
  2. 在 if 陳述中,使用關鍵字 and 添加第二個條件,檢查當前的 WalkSpeed 值是否小於 50。添加增益後,最快的 WalkSpeed 值將為 60。

    檢查當前 WalkSpeed 是否為 50 或更少
    if humanoid and humanoid.WalkSpeed <= 50 then
    humanoid.WalkSpeed += 10
    end

微調速度增益

每次觸碰增益道具時都會調用 onTouch。每一步或最輕微的彈跳都會觸發 Touched 事件並調用連接的函數。部件的屬性 CanTouch 可以防止 Touched 事件觸發。利用 CanTouch,並在每次啟用後關閉速度增益一秒鐘。

  1. 在施加增益後,將部件的 CanTouch 屬性設置為 false。進行遊玩測試,確保增益僅應用一次。

    禁用速度增益
    local speedBoost = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid and humanoid.WalkSpeed <= 50 then
    humanoid.WalkSpeed += 10
    speedBoost.CanTouch = false
    end
    end
    speedBoost.Touched:Connect(onTouch)
  2. 使用 task.wait(1) 暫停腳本一秒鐘,然後將 CanTouch 設置為 true。進行遊玩測試,確保速度增益可以在一秒後重新應用。

    完成的腳本
    local speedBoost = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid and humanoid.WalkSpeed <= 50 then
    humanoid.WalkSpeed += 10
    speedBoost.CanTouch = false
    task.wait(1)
    speedBoost.CanTouch = true
    end
    end
    speedBoost.Touched:Connect(onTouch)
  3. 在完成的腳本中調整值。WalkSpeed 可以上升到 100。默認的 WalkSpeed 值為 16。

總結

關鍵字 and 可用於要求多個條件在執行代碼塊之前滿足,例如一個值大於 0 且小於 100。或者如果存在 Humanoid 且其 WalkSpeed 小於或等於 50。

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