ROBLOX Studio:我如何让这个 NPC 跟随最近的玩家,这个玩家总是不同的,而不是有时 运行 撞到墙上?

ROBLOX Studio: How do I make this NPC follow the nearest player which is always different and not sometimes run into the wall?

ROBLOX Studio:我如何让这个 NPC 跟随最近的玩家总是不同的而不是有时 运行 撞墙?看起来你的 post 主要是代码;请添加更多详细信息。

 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()

现在为了获得最近的玩家,您可以创建一个 table 来存储每个玩家与您的 NPC 的距离:local playerDistances = {}。现在您可以在所有 NPC 移动代码周围使用 while 循环(以便 NPC 继续跟随玩家)。在检查温度、人类和 human.Health 的 if 语句中,您可以通过 table.insert(playerDistances,(<Player HumanoidRootPart>.Position-<NPC HumanoidRootPart>.Position).magnitude)[=23 添加玩家 HumanoidRootPart(存储玩家位置的部分)与 NPC 的距离=]

您可以通过在 while 循环的 end 之前执行 table.clear(playerDistances) 每次循环时刷新距离的 table。这确保 table 中没有不必要的旧数据,这些数据会扰乱你的 NPC。

然后您可以通过 playerDistances[1]

访问最近的玩家

现在为了不让 NPC 运行 撞墙,我建议使用 Roblox Lua 的 PathfindingService。您可以使用 :CreatePath(), :GetWaypoints(), :MoveTo(), and :MoveToFinished:Wait() 来持续确保 NPC 计算出一条开放路径并且可以到达玩家。以下是 PathfindingService 上 Developer Wiki 页面的一些链接:

https://developer.roblox.com/en-us/api-reference/class/PathfindingService
^^ 所有功能、属性等

https://developer.roblox.com/en-us/articles/Pathfinding
^^ 如何使用 PathfindingService