ROBLOX工作室:如何让这个NPC跟随最近的玩家,而不会有时撞墙?

ROBLOX工作室:如何让这个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
点赞
用户15250066
用户15250066

首先,确保在第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 循环的 end 之前执行 table.clear(playerDistances) 来刷新距离表,这样可以确保表中没有不必要的旧数据会干扰您的 NPC。

然后,您可以通过执行 playerDistances[1] 来访问最近的玩家。

现在,为了避免 NPC 撞到墙壁,我建议使用 Roblox Lua 的 PathfindingService。您可以使用 :CreatePath()、:GetWaypoints()、:MoveTo() 和 :MoveToFinished:Wait() 来不断确保 NPC 计算出开放路径并能到达玩家。下面是一些关于 PathfindingService 的开发人员 Wiki 页面的链接:

https://developer.roblox.com/en-us/api-reference/class/PathfindingService

^^ 所有的函数、属性等。

https://developer.roblox.com/en-us/articles/Pathfinding

^^ 如何使用 PathfindingService

2021-05-05 00:34:31