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

Roblox:检测玩家触碰部件时是否处于移动状态

Roblox触碰检测移动代码失效原因与修复方案

失效原因

  • 角色对象获取错误:你代码里取的game.StarterPlayer.StarterCharacterScripts是角色脚本的模板文件夹,不是玩家进入游戏后生成的实际角色实例,根本找不到对应玩家的Humanoid。
  • 未过滤触碰对象:Touched事件会响应所有碰撞的部件(比如场景里的道具、其他NPC),没判断是不是玩家的身体部件,容易触发无效逻辑。
  • 重复绑定事件:每次触碰都会绑定一次Running事件,多次触碰后会堆积大量事件监听,导致打印信息混乱甚至性能问题。

修复后的代码

workspace.corridor.Monster.EyeHitbox.Touched:Connect(function(hit)
    -- 从触碰的部件找到所属的角色
    local character = hit.Parent
    if not character:FindFirstChild("Humanoid") then
        -- 如果不是带Humanoid的角色,直接退出
        return
    end

    -- 获取玩家对象,确认是玩家角色
    local player = game.Players:GetPlayerFromCharacter(character)
    if not player then
        return
    end

    -- 先移除之前可能存在的监听(避免重复绑定)
    local humanoid = character.Humanoid
    if humanoid:GetAttribute("RunningConnection") then
        humanoid:GetAttribute("RunningConnection"):Disconnect()
    end

    -- 绑定Running事件并保存连接引用
    local connection = humanoid.Running:Connect(function(speed)
        if speed > 0.1 then
            print(player.Name .. " 正在移动")
        else
            print(player.Name .. " 处于静止")
        end
    end)
    humanoid:SetAttribute("RunningConnection", connection)
end)

额外说明

  • 每次绑定Running事件前先断开旧连接,防止重复触发。
  • 通过GetPlayerFromCharacter确认触碰的是玩家角色,避免误触发其他NPC或道具。
  • 打印信息加上玩家名称,方便区分不同玩家的状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:22:02