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
相关产品推荐
相关产品推荐

