ROBLOX工作室:如何让这个NPC跟随最近的玩家,而不会有时撞墙?
2021-5-4 16:14:0
收藏:0
阅读:232
评论:1
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
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

首先,确保在第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。