如果語句有多個要求必須為真才能執行程式碼。關鍵字 and 允許你組合陳述。以下代碼首先評估兩加二是否等於六,然後評估四是否不等於六。如果兩個陳述都為真,則程式碼將會執行。
-- 不會執行if 2 + 2 == 6 and 4 ~= 6 thenprint("兩個陳述都是正確的")end-- 會執行if 4 + 2 == 6 and 4 ~= 6 thenprint("兩個陳述都是正確的")end
創建一個增強道具
增強道具是在遊戲中提供玩家特殊能力的物品,例如飛行、隱形或加速。這個增強道具將每次玩家觸碰時提升其行走速度。持續施加增強可能會讓玩家速度過快,因此我們將使用 and 來控制最大行走速度限制。
設置增強道具
使用以下代碼與一個簡單的零件或模型,如水晶、硬幣或發光的霓虹球。
創建一個名為 Powerup 的新零件,並插入一個名為 WalkSpeedManager 的腳本。
宣告一個名為 speedBoost 的變數並分配給腳本的父物件。
-- 被觸碰時給予臨時的速度增強local speedBoost = script.Parent設置一個名為 onTouch 的函數並將其連接到父物件的 Touched 事件。然後進行遊玩測試並檢查你的工作。
local speedBoost = script.Parentlocal function onTouch(otherPart)print("某物觸碰了 speedBoost")endspeedBoost.Touched:Connect(onTouch)WalkSpeed 屬性位於 Humanoid 物件上。使用在創建陷阱部件時相同的模式來創建一個條件,以檢查 Humanoid 物件。
尋找 Humanoid 部件local function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid thenprint("找到了 Humanoid")endend
加速玩家
這個增強將使每次觸碰增強道具時,角色走得更快。這將迅速變得非常非常快。關鍵字 and 將確保玩家不會加速過快,僅在玩家的速度低於一定值時啟用速度增強。
如果找到了 Humanoid,則獲取當前的 WalkSpeed 值並加上 10。進行遊玩測試,你的角色將在每次觸碰速度增強時變得更快。
增加當前 WalkSpeedlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid thenhumanoid.WalkSpeed += 10endendspeedBoost.Touched:Connect(onTouch)在 if 語句中,使用關鍵字 and 添加第二個條件,當前的 WalkSpeed 值必須小於 50。在添加增強之後,最快的 WalkSpeed 值將是 60。
檢查當前 WalkSpeed 是否為 50 或更少if humanoid and humanoid.WalkSpeed <= 50 thenhumanoid.WalkSpeed += 10end
微調速度增強
每次觸碰增強道具時,onTouch 會被調用。每一步或稍微的彈跳都會觸發 Touched 事件並調用連接的函數。該零件的屬性 CanTouch 可以防止 Touched 事件被觸發。利用 CanTouch,每次啟動後關閉速度增強一秒鐘。
在應用增強後,將零件的 CanTouch 屬性設置為 false。進行遊玩測試,確保增強僅應用一次。
禁用速度增強local speedBoost = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid and humanoid.WalkSpeed <= 50 thenhumanoid.WalkSpeed += 10speedBoost.CanTouch = falseendendspeedBoost.Touched:Connect(onTouch)使用 task.wait(1) 暫停腳本一秒鐘,然後將 CanTouch 設置回 true。進行遊玩測試,確保增強在一秒鐘後可以重新應用。
完成的腳本local speedBoost = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid and humanoid.WalkSpeed <= 50 thenhumanoid.WalkSpeed += 10speedBoost.CanTouch = falsetask.wait(1)speedBoost.CanTouch = trueendendspeedBoost.Touched:Connect(onTouch)在完成的腳本中調整數值。WalkSpeed 可以升高至 100。默認的 WalkSpeed 值為 16。
總結
關鍵字 and 可以用來要求多個條件必須滿足才能運行一段程式碼,例如某個值大於 0 且小於 100。或者如果存在 Humanoid 以及它的 WalkSpeed 小於或等於 50。