【发布时间】:2017-06-29 18:14:40
【问题描述】:
我想在玩家站在零件上时更改零件的颜色,但我可以将脚本放在工作区中并从事件中识别零件,而不是将脚本放在零件内,例如触摸人形机器人或其他东西吗?
原因是我有 100 个部件需要对触摸事件做出反应,所以我不想在每个部件中放置相同的脚本。
伪代码可能是
玩家触摸部分事件被触发 从事件中识别零件并更改零件颜色
谢谢
【问题讨论】:
我想在玩家站在零件上时更改零件的颜色,但我可以将脚本放在工作区中并从事件中识别零件,而不是将脚本放在零件内,例如触摸人形机器人或其他东西吗?
原因是我有 100 个部件需要对触摸事件做出反应,所以我不想在每个部件中放置相同的脚本。
伪代码可能是
玩家触摸部分事件被触发 从事件中识别零件并更改零件颜色
谢谢
【问题讨论】:
正如 M. Ziegenhorn 所写,您可以将脚本放在角色中或直接放在脚中。这将是实现这一目标的“最简单”的方式。
但是,您也可以轻松地将函数连接到每个部分。 在下面的代码中,我们检查了工作区中名为“TouchParts”的模型,该模型(假设)包含您想要将触摸功能绑定到的部分。
function Touched(self, Hit)
if Hit and Hit.Parent and Hit.Parent:FindFirstChildOfClass'Humanoid' then
-- We know it's a character (or NPC) since it contains a Humanoid
-- Do your stuff here
print(Hit.Parent.Name, 'hit the brick', self:GetFullName())
self.BrickColor = BrickColor.new('Bright red')
end
end
for _, object in pairs(workspace.TouchParts:GetChildren()) do
if object:IsA'BasePart' then
object.Touched:connect(function(Hit)
Touched(object, Hit)
end)
end
end
这样做意味着你的角色中任何接触部件的东西都会触发 Touched 事件,所以你必须添加一个检查来查看接触的部分是否是腿。
将函数绑定到每个部分而不是腿的优点在于,该函数仅在您实际触摸其中一个预期部分时调用,而不是您触摸的任何部分。但是,随着您连接的部件数量增加,将触发并存储在内存中的事件数量也会增加。在您使用的规模上可能不明显,但值得牢记。
【讨论】:
我已经有一段时间没有在 roblox 上编写代码了,所以请原谅我犯的任何错误。
local parent = workspace.Model --This is the model that contains all of that parts you are checking.
local deb = 5 --Simple debounce variable, it's the minimum wait time in between event fires, in seconds.
local col = BrickColor.new("White") --The color you want to change them to once touched.
for _,object in next,parent:GetChildren() do --Set up an event for each object
if object:IsA("BasePart") then --Make sure it's some sort of part
spawn(function() --Create a new thread for the event so that it can run separately and not yield our code
while true do --Create infinite loop so event can fire multiple times
local hit = object.Touched:wait() --Waits for the object to be touched and assigns what touched it to the variable hit
local player = game.Players:GetPlayerFromCharacter(hit.Parent) --Either finds the player, or nil
if player then --If it was indeed a player that touched it
object.BrickColor = BrickColor.new(col) --Change color; note this is also where any other code that should run on touch should go.
end
wait(deb) --Wait for debounce
end
end)
end
end
这可能是最有效的方法之一。
【讨论】:
当玩家站在一个方块上时,值“FloorMaterial”(在 Humanoid 中)会告诉你用户站在什么材料上,但如果用户没有站在任何东西上,这个值将是 nil .
另一种有效的方法是使用光线。您需要从 HumanoidRootPart 创建一条射线。
示例:
IsOnGround=function()
local b=false;
local range=6;
local char=game:service("Players").LocalPlayer.Character;
local root=char:WaitForChild("HumanoidRootPart",1);
if root then
local ray=Ray.new(root.CFrame.p,((root.CFrame*CFrame.new(0,-range,0)).p).unit*range);
local ignore={char};
local hit,pos=workspace:FindPartOnRayWithIgnoreList(ray,ignore,false,false);
pcall(function()
if hit then
b=true;
end
end)
else
print("root not found");
end
return b;
end
这会从 HumanoidRootPart 向应该是地面的方向投射一条光线,距离为 6 个螺柱。
遗憾的是,据我所知,这种方法对 R15 字符不是很有效。
【讨论】: