ROBLOX Studio:如何让这个 NPC 跟随最近的玩家(总是不同的)并且有时不会撞墙?看起来你的帖子主要是代码;请添加更多详细信息。
local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = math.huge
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
while true do
wait(math.random(1,5))
local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
if target ~= nil then
script.Parent.Humanoid:MoveTo(target.Position, target)
end
end
首先,确保第 5 行有
game.Workspace:GetChildren()
而不是 game.Workspace:children()
现在为了获取最近的玩家,您可以创建一个表来存储每个玩家与 NPC 的距离:
local playerDistances = {}
。现在,您可以对所有 NPC 移动代码使用 while 循环(以便 NPC 继续跟随玩家)。在检查 temp、 human 和 human.Health 的 if 语句中,您可以通过执行 table.insert(playerDistances,(<Player HumanoidRootPart>.Position-<NPC HumanoidRootPart>.Position).magnitude)
添加玩家 HumanoidRootPart(存储玩家位置的部分)与 NPC 的距离
然后,您可以在每次循环时通过在 while 循环的
table.clear(playerDistances)
之前执行 end
来刷新距离表。这可以确保表中没有不必要的旧数据,这些数据会扰乱您的 NPC。
然后您可以通过执行以下操作来访问最近的玩家
playerDistances[1]
现在为了不让NPC碰壁,我建议使用Roblox Lua的
PathfindingService
。您可以使用 :CreatePath(), :GetWaypoints(), :MoveTo(), and :MoveToFinished:Wait()
持续确保 NPC 计算出一条开放路径并可以到达玩家。以下是 PathfindingService
上开发者 Wiki 页面的一些链接:
https://developer.roblox.com/en-us/api-reference/class/PathfindingService
^^ 所有功能、属性等
https://developer.roblox.com/en-us/articles/Pathfinding
^^ 使用方法
PathfindingService
请注意,您还应该将玩家 HumanoidRootPart 添加到表中,因为您不能仅根据距离创建一条路径,只需使用上述相同方法添加另一个列表,并将玩家而不是距离附加到此列表中即可。