評估多個陳述

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

如果語句有多個要求必須為真才能執行程式碼。關鍵字 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 是我們在美國及其他國家地區的部分註冊與未註冊商標。