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

Roblox中Part的Touched事件无法触发伤害问题求助

问题分析与修复方案

核心问题点

  • 全局冷却变量冲突:debounceDMG是全局变量,所有玩家共用,一个玩家触发攻击冷却后,其他玩家在冷却时间内无法造成伤害,需为单次攻击独立设置冷却。
  • Hitbox碰撞检测失效:Anchored = true会让Part脱离物理模拟,无法触发Touched事件,必须改为Anchored = false,同时保留CanCollide = false避免干扰角色移动。
  • 内存泄漏隐患:每次攻击创建的Heartbeat连接在hitbox销毁后未断开,会持续占用资源,需保存连接并在清理时断开。
  • 数据访问无容错:直接访问plr.Data.Forca.Value可能因玩家数据未加载完成导致读取失败,需添加存在性检查。
  • 重复伤害问题:Touched事件可能多次触发同一目标,需记录已攻击对象避免重复减血。

修复后的代码

local rep = game:GetService("ReplicatedStorage")
local runService = game:GetService("RunService")

rep.Combate.Soco.OnServerEvent:Connect(function(plr)
    -- 检查角色与数据是否就绪
    local char = plr.Character or plr.CharacterAdded:Wait()
    local humanoid = char.Humanoid
    local dataFolder = plr:FindFirstChild("Data")
    local forcaValue = dataFolder and dataFolder:FindFirstChild("Forca")
    if not forcaValue then return end -- 数据未加载则终止流程

    local isLeftHand = math.random(1,2) == 2
    local anim = humanoid:LoadAnimation(isLeftHand and script.Left or script.Animation)
    anim:Play()

    -- 创建Hitbox
    local hitbox = Instance.new("Part")
    hitbox.Parent = workspace
    hitbox.Transparency = 1
    hitbox.Anchored = false -- 关键:关闭Anchored才能触发物理碰撞
    hitbox.CanCollide = false
    hitbox.Size = Vector3.new(2.5,2.5,2.5)
    hitbox.Massless = true -- 避免Hitbox影响角色物理状态

    -- 单次攻击的冷却与已攻击目标记录
    local canDealDamage = true
    local attackedTargets = {}

    -- 绑定Hitbox到对应手部
    local heartbeatConn = runService.Heartbeat:Connect(function()
        local targetHand = isLeftHand and char.LeftHand or char.RightHand
        if targetHand then
            hitbox.CFrame = targetHand.CFrame
        end
    end)

    hitbox.Touched:Connect(function(hit)
        local targetHumanoid = hit.Parent:FindFirstChild("Humanoid")
        if targetHumanoid and targetHumanoid ~= humanoid and canDealDamage and not attackedTargets[targetHumanoid] then
            canDealDamage = false
            attackedTargets[targetHumanoid] = true
            -- 计算并施加伤害,确保生命值不低于0
            local damage = forcaValue.Value + 5
            targetHumanoid.Health = math.max(targetHumanoid.Health - damage, 0)
            task.wait(0.5)
            canDealDamage = true
        end
    end)

    -- 攻击结束后清理资源
    task.wait(0.3)
    heartbeatConn:Disconnect() -- 断开心跳连接,避免内存泄漏
    hitbox:Destroy()
end)

额外优化建议

  • 用Attachment+WeldConstraint替代RunService更新位置,物理同步更稳定且性能更好。
  • 绑定动画结束事件,让Hitbox存在时长与动画匹配,而非固定0.3秒。
  • 对Soco事件添加权限验证,防止恶意客户端频繁触发攻击。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:40:17