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

如何实现两名Roblox玩家踩在部件上均获得胜利?

问题分析与解决方案

原脚本的核心问题出在全局防抖变量db:

  • 加wait(1)时,第一个触发的玩家会把db设为false,期间其他玩家触发事件会直接跳过,导致仅一人获奖。
  • 不加wait时,Touched事件会因碰撞检测连续触发多次,同一个玩家会重复触发奖励逻辑,导致胜利次数重复增加。

要实现「两名玩家同时触碰部件时各得1次胜利、无冷却且不重复奖励」,需要按玩家个体追踪奖励状态,而非用全局防抖。

修正后的代码

-- 用于记录当前已获得胜利的玩家
local awardedPlayers = {}

-- 触碰事件处理
script.Parent.Touched:Connect(function(hit)
    -- 检测碰撞对象是否为玩家角色
    local humanoid = hit.Parent:FindFirstChild("Humanoid")
    if not humanoid then return end
    
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if not player then return end
    
    -- 检查该玩家是否已获得过本次触碰的奖励
    if not awardedPlayers[player] then
        -- 增加胜利次数
        player.leaderstats.Wins.Value += 1
        -- 标记该玩家已获奖
        awardedPlayers[player] = true
    end
end)

-- 离开部件时移除标记,允许玩家下次触碰再次获奖
script.Parent.TouchEnded:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChild("Humanoid")
    if not humanoid then return end
    
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then
        awardedPlayers[player] = nil
    end
end)

代码逻辑说明

  • 使用awardedPlayers表以玩家实例作为键,记录每个玩家是否已在本次触碰中获得奖励,确保同一玩家单次触碰只加1次胜利。
  • TouchEnded事件用于在玩家离开部件时清除标记,让玩家离开后再次触碰部件仍能获得奖励,满足无冷却需求。
  • 增加空值判断(比如player可能为nil的情况),避免脚本运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:12:07