如何让绑定Humanoid Root Part的Hitbox随角色移动并解决自伤问题
解决Hitbox随角色移动时自伤的问题
问题根源
你的代码存在两个核心问题导致自伤:
- 没有在Hitbox的
Touched事件中排除当前角色自身的部件检测 - Hitbox同时设置了
Anchored = true和WeldConstraint,物理属性冲突导致位置同步异常,角色移动时Hitbox易与自身部件误触发碰撞
解决方案
修改后的服务器脚本
local rs = game:GetService("ReplicatedStorage") local events = rs:WaitForChild("Events") local hitboxEvent = events:WaitForChild("Hitbox") function newHitbox(character, size, offset, damage, linger) local hrp = character:FindFirstChild("HumanoidRootPart") if hrp == nil then return end local weld = Instance.new("WeldConstraint") local hitbox = Instance.new("Part") weld.Part0 = hrp weld.Part1 = hitbox weld.Parent = hitbox -- 将Weld绑定到Hitbox,销毁时自动清理 -- 修正物理属性,确保Hitbox正常跟随角色移动 hitbox.CanCollide = false hitbox.CanQuery = true -- 原代码设为false会导致Touched事件失效,必须改为true hitbox.Massless = true hitbox.Anchored = false -- 取消锚定,依赖WeldConstraint实现跟随 hitbox.Transparency = 1 -- 隐藏Hitbox,避免视觉干扰 hitbox.Size = size hitbox.CFrame = hrp.CFrame + hrp.CFrame.LookVector * offset.X + Vector3.new(0, offset.Y) hitbox.Parent = character hitbox.Touched:Connect(function(hit) -- 优先排除自身角色,彻底解决自伤问题 if hit.Parent == character then return end local hitHumanoid = hit.Parent:FindFirstChild("Humanoid") if hitHumanoid == nil then return end -- 检查是否已命中过该角色,避免重复伤害 local hasHit = false for _, v in pairs(hitbox:GetChildren()) do if v:IsA("ObjectValue") and v.Value == hit.Parent then hasHit = true break end end if hasHit then return end local hitCounter = Instance.new("ObjectValue") hitCounter.Value = hit.Parent hitCounter.Parent = hitbox hitHumanoid:TakeDamage(damage) end) task.wait(linger) hitbox:Destroy() end hitboxEvent.OnServerEvent:Connect(function(plr, size, offset, damage, linger) newHitbox(plr.Character, size, offset, damage, linger) end)
关键修改说明
- 排除自身角色检测:在
Touched事件最开头添加hit.Parent == character的判断,直接跳过自身部件的碰撞检测,从根源解决自伤问题 - 修复物理属性冲突:取消Hitbox的
Anchored设置,让WeldConstraint正常生效,保证Hitbox精准跟随角色移动;同时修正CanQuery = true,确保Touched事件能正常触发 - 优化细节:添加
Transparency = 1隐藏Hitbox,将Weld绑定到Hitbox父级避免内存泄漏,简化已命中角色的判断逻辑提升效率
LocalScript无需修改,使用上述服务器脚本即可替代临时减速的妥协方案,实现功能的同时保证代码健壮性。
内容的提问来源于stack exchange,提问作者Relaxing Gaming
相关产品推荐
相关产品推荐

