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

如何防止玩家自身Humanoid被发射的Part击杀?

问题分析与修复方案

你的代码存在两处核心问题,导致无法排除玩家自身受伤害的情况:

  1. Humanoid查找路径错误:触发Touched事件的hsit是角色的身体部位(比如手臂、腿部),而Humanoid并不在这些部位的子节点中,而是在角色模型的根节点。直接用hsit:FindFirstChild("Humanoid")大概率返回nil,对比逻辑自然失效。
  2. 冷却逻辑混乱:将冷却标记db放在Touched事件回调内,且在RemoteEvent连接外层重复设置,会导致多次触发事件时冷却逻辑冲突。

同时优化了碰撞判断的严谨性,避免同一子弹多次触发扣血。修复后的代码如下:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage.RemoteEvent
local Debris = game:GetService("Debris")

RemoteEvent.OnServerEvent:Connect(function(Player, Hit)
    -- 前置检查:确保角色、工具存在,避免报错
    local Character = Player.Character
    if not Character or not Character:FindFirstChild("Humanoid") then return end
    local Tool = Character:FindFirstChild("Tool")
    if not Tool or not Tool:FindFirstChild("Part") then return end

    -- 创建子弹Part
    local Shot = Instance.new("Part")
    Shot.BrickColor = BrickColor.new("New Yeller")
    Shot.CanCollide = false
    Shot.Position = Tool.Part.Position
    Shot.Shape = Enum.PartType.Block
    Shot.Size = Vector3.new(0.34, 0.228, 2)
    Shot.Parent = workspace

    -- 添加推进力组件
    local Attach = Instance.new("Attachment", Shot)
    local VectorForce = Instance.new("VectorForce")
    VectorForce.Attachment0 = Attach
    VectorForce.RelativeTo = Enum.ActuatorRelativeTo.World
    VectorForce.Force = CFrame.lookAt(Tool.Part.Position, Hit.Position).LookVector * 500
    VectorForce.Parent = Shot

    -- 单子弹碰撞标记:防止同一子弹多次扣血
    local hasDamaged = false
    Shot.Touched:Connect(function(hit)
        if hasDamaged then return end

        -- 多层查找Humanoid:覆盖碰撞到角色子部件(如衣服)的场景
        local Humanoid = hit.Parent:FindFirstChild("Humanoid")
        if not Humanoid then
            Humanoid = hit.Parent.Parent:FindFirstChild("Humanoid")
        end
        if not Humanoid or Humanoid.Health <= 0 then return end

        -- 通过玩家对象判断:排除开枪者自身
        local HitPlayer = game.Players:GetPlayerFromCharacter(Humanoid.Parent)
        if HitPlayer == Player then return end

        -- 执行扣血操作
        Humanoid.Health -= 5
        hasDamaged = true
    end)

    -- 自动销毁子弹
    Debris:AddItem(Shot, 3)
end)

关键修改说明:

  • 修正Humanoid查找逻辑:从hit.Parent和hit.Parent.Parent两层查找,覆盖碰撞到角色子部件的场景。
  • 基于玩家对象判断:用GetPlayerFromCharacter获取碰撞对象所属玩家,直接对比是否为开枪者,逻辑更可靠。
  • 单子弹独立冷却:给每个子弹单独设置hasDamaged标记,避免不同子弹间的冷却干扰,同时防止同一子弹多次触发扣血。
  • 增加前置校验:提前判断角色、工具是否存在,避免运行时抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:27:24