去抖動模式

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

一個去抖動模式是一種編碼技巧,用於防止函數執行過於頻繁或防止輸入觸發多次。以下的腳本場景示範了去抖動作為最佳實踐。

偵測碰撞

假設您想創建一個危險的陷阱部件,當被觸摸時會造成10點傷害。初始實現可能會使用基本的 BasePart.Touched 連接和 damagePlayer 函數,如下所示:

腳本 - 傷害玩家

local part = script.Parent
local function damagePlayer(otherPart)
print(part.Name .. " 與 " .. otherPart.Name .. " 碰撞")
local humanoid = otherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid then
humanoid.Health -= 10 -- 減少玩家健康
end
end
part.Touched:Connect(damagePlayer)

雖然乍看之下邏輯上合理,但測試會顯示 Touched 事件會根據微小的物理碰撞快速多次觸發。

為了避免在首次接觸時造成過多的傷害,您可以添加一個去抖動系統,通過實例屬性強制執行伤害的冷卻時間。

腳本 - 使用去抖動傷害玩家

local part = script.Parent
local RESET_TIME = 1
local function damagePlayer(otherPart)
print(part.Name .. " 與 " .. otherPart.Name .. " 碰撞")
local humanoid = otherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid then
if not part:GetAttribute("Touched") then
part:SetAttribute("Touched", true) -- 將屬性設置為 true
humanoid.Health -= 10 -- 減少玩家健康
task.wait(RESET_TIME) -- 等待重置時間
part:SetAttribute("Touched", false) -- 重置屬性
end
end
end
part.Touched:Connect(damagePlayer)

觸發聲音

在處理音效時,去抖動也很有用,例如在兩個部件碰撞時播放音效 (Touched),或在用戶與螢幕上的按鈕互動時在 Activated 事件播放音效。在這兩種情況下,調用 Sound:Play() 會從音軌的開始播放,而 —如果沒有去抖動系統 — 這可能會導致音效在短時間內多次播放。

為了防止聲音重疊,您可以使用 IsPlaying 屬性來去抖動 Sound 對象:

腳本 - 使用去抖動播放碰撞音效

local projectile = script.Parent
local function playSound()
-- 找到部件上的子聲音
local sound = projectile:FindFirstChild("Impact")
-- 僅在未播放時播放聲音
if sound and not sound.IsPlaying then
sound:Play()
end
end
projectile.Touched:Connect(playSound)
腳本 - 使用去抖動播放按鈕點擊音效

local button = script.Parent
local function onButtonActivated()
-- 找到按鈕上的子聲音
local sound = button:FindFirstChild("Click")
-- 僅在未播放時播放聲音
if sound and not sound.IsPlaying then
sound:Play()
end
end
button.Activated:Connect(onButtonActivated)

拾取效果

遊戲通常包含像醫療包、彈藥包等可收藏的拾取物。在設計這些拾取物以便玩家可以不斷取得時,應該在拾取刷新和重新啟用之前添加“冷卻”時間。

偵測碰撞類似,您可以使用實例屬性來管理去抖動狀態,並通過改變部件的 Transparency 來可視化冷卻時間。

腳本 - 使用去抖動的健康拾取

local part = script.Parent
part.Anchored = true
part.CanCollide = false
local COOLDOWN_TIME = 5
local function healPlayer(otherPart)
local humanoid = otherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid then
if not part:GetAttribute("CoolingDown") then
part:SetAttribute("CoolingDown", true) -- 將屬性設置為 true
humanoid.Health += 25 -- 增加玩家健康
part.Transparency = 0.75 -- 使部件半透明以指示冷卻狀態
task.wait(COOLDOWN_TIME) -- 等待冷卻持續時間
part.Transparency = 0 -- 將部件重置為完全不透明
part:SetAttribute("CoolingDown", false) -- 重置屬性
end
end
end
part.Touched:Connect(healPlayer)
©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。