You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ProximityPrompt添加仅针对本地玩家的冷却机制?

实现ProximityPrompt的本地玩家冷却机制并解决物品重复问题

核心思路

  • 冷却逻辑放在客户端处理,仅限制触发操作的本地玩家,不影响其他玩家使用同一个ProximityPrompt
  • 物品发放逻辑移交服务器处理,从根源避免客户端重复请求导致的物品重复问题

具体实现代码

客户端脚本(挂载到ProximityPrompt对象上)

local ProximityPrompt = script.Parent
local COOLDOWN_DURATION = 5 -- 自定义冷却时长(秒)
local isCoolingDown = false

ProximityPrompt.Triggered:Connect(function(player)
    -- 只响应本地玩家的触发请求
    if player ~= game.Players.LocalPlayer then return end
    -- 处于冷却状态时直接返回
    if isCoolingDown then return end

    isCoolingDown = true
    -- 向服务器发送物品请求
    game.ReplicatedStorage.RequestPizza:FireServer()
    
    -- 本地计时结束后解除冷却
    task.wait(COOLDOWN_DURATION)
    isCoolingDown = false
end)

服务器脚本(挂载到ServerScriptService中)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")

-- 创建远程事件,用于接收客户端的物品请求
local RequestPizza = Instance.new("RemoteEvent")
RequestPizza.Name = "RequestPizza"
RequestPizza.Parent = ReplicatedStorage

-- 服务器侧记录玩家冷却,防止作弊触发
local playerCooldowns = {}
local SERVER_COOLDOWN = 4.5 -- 比客户端冷却略短,适配网络延迟

RequestPizza.OnServerEvent:Connect(function(player)
    local currentTime = os.time()
    -- 验证服务器侧冷却状态
    if playerCooldowns[player] and currentTime - playerCooldowns[player] < SERVER_COOLDOWN then
        return
    end
    playerCooldowns[player] = currentTime

    -- 克隆披萨物品(假设披萨存放在ServerStorage)
    local pizzaTemplate = ServerStorage:FindFirstChild("Pizza")
    if not pizzaTemplate then return end

    -- 检查玩家背包是否已有该物品,避免重复添加
    local existingPizza = player.Backpack:FindFirstChild(pizzaTemplate.Name)
    if not existingPizza then
        local newPizza = pizzaTemplate:Clone()
        newPizza.Parent = player.Backpack
    end
end)

关键细节说明

  • 客户端冷却确保玩家自己无法重复触发,其他玩家不受该冷却限制
  • 服务器双验证:既做冷却检查防止作弊,又检查背包物品状态避免重复发放
  • 服务器冷却时长略短于客户端,防止因网络延迟导致客户端冷却结束后服务器仍拒绝请求

内容的提问来源于stack exchange,提问作者Ponda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:35:18