Roblox镐子工具求助:已接触Coal部件点击无法触发现金生成
Roblox镐子工具功能修复方案
你的代码逻辑核心问题在于触发时机错误——当前是镐子刚接触Coal时自动触发现金,但你需要的是玩家点击镐子时,检查是否正接触Coal再触发现金。原代码绑定的Touched事件仅在部件开始接触的瞬间触发,完全不符合需求。
修复代码
把触发逻辑从Touched事件转移到工具的Activated事件(玩家点击工具时触发),在点击时检查当前镐子是否接触Coal部件:
local tool = script.Parent local ReplicatedStorage = game:GetService("ReplicatedStorage") local UpdateMoneyEvent = ReplicatedStorage.RemoteEvents.UpdateMoney -- 监听工具被点击激活的事件 tool.Activated:Connect(function() -- 获取镐子手柄当前接触的所有部件 local touchingParts = tool.Handle:GetTouchingParts() -- 遍历接触列表,查找Coal部件 for _, part in ipairs(touchingParts) do if part.Name == "Coal" then UpdateMoneyEvent:FireServer(100) print("镐子接触Coal,已生成100现金!") -- 找到目标后退出循环,避免重复触发 break end end end)
额外优化建议
- 适配无碰撞Coal部件:如果Coal的
CanCollide属性为false,GetTouchingParts()无法检测到它,改用workspace:GetPartsInPart()替代:-- 替换原touchingParts的获取方式 local touchingParts = workspace:GetPartsInPart(tool.Handle) - 添加冷却防刷钱:避免玩家疯狂点击刷取现金,增加冷却机制:
local tool = script.Parent local ReplicatedStorage = game:GetService("ReplicatedStorage") local UpdateMoneyEvent = ReplicatedStorage.RemoteEvents.UpdateMoney local isOnCooldown = false local cooldownDuration = 1 -- 冷却1秒 tool.Activated:Connect(function() if isOnCooldown then return end isOnCooldown = true local touchingParts = tool.Handle:GetTouchingParts() for _, part in ipairs(touchingParts) do if part.Name == "Coal" then UpdateMoneyEvent:FireServer(100) print("镐子接触Coal,已生成100现金!") break end end task.wait(cooldownDuration) isOnCooldown = false end)
内容的提问来源于stack exchange,提问作者BogoBob273
相关产品推荐
相关产品推荐

