首页 分享 用代码做简单的宠物跟随功能,小宠物是如何一直跟随玩家的

用代码做简单的宠物跟随功能,小宠物是如何一直跟随玩家的

来源:萌宠菠菠乐园 时间:2024-10-25 02:02

1、首先,创建一个部件,命名为Root(部件一定要命名为Root)

2、随后将部件分组,命名为pet(不一定要pet,可随意命名),随后在分组下创建一个Script脚本,如下图:
image

3,、Script脚本代码如下:

local pet = script.Parent--宠物 local avatar = pet.Parent local root = pet.Root local RunService = game:GetService("RunService") local AlignOrientation = nil local Attachment = nil local BodyPosition = nil --初始化约束 if not root:FindFirstChild("AlignOrientation") thenAlignOrientation = Instance.new("AlignOrientation",root) elseAlignOrientation = root.AlignOrientation end if not root:FindFirstChild("Attachment") thenAttachment = Instance.new("Attachment",root) elseAttachment = root.Attachment end if not root:FindFirstChild("BodyPosition") thenBodyPosition = Instance.new("BodyPosition",root) elseBodyPosition = root.BodyPosition end --检测到玩家就跟随 RunService.Stepped:Connect(function()avatar = pet.Parentlocal hroot = avatar:FindFirstChild("HumanoidRootPart")local humanoid = avatar:FindFirstChild("Humanoid")if avatar and hroot and humanoid then--判断父级对象也就是角色存在BodyPosition.P = 5000local t = avatar.HumanoidRootPart.Orientation.Y*math.pi/180 --玩家当前朝向于z轴正向夹角local quaright = Vector3.new(math.sin(t),0,math.cos(t))*(1) --玩家朝向单位向量,小球初始速度的单位向量local tarpos = avatar.HumanoidRootPart.Position + quaright*4 + Vector3.new(0,1.5,0)--计算目标位置,相对角色的右侧偏高1米AlignOrientation.Attachment0 = AttachmentAlignOrientation.Attachment1 = avatar.HumanoidRootPart.RootRigAttachmentBodyPosition.Position = tarposend end)

4、最后一步骤来了,运行游戏,然后切换成当前服务器:
image

把宠物拖到角色下:
image

image

换回当前客户端:
image

看看效果!
image
运行成功了!

5、最后说明一下!为什么上面的第二步要分组?为什么不直接一个部件就行?
这样做是为了拓展需求,你的一个宠物不可能是一个部件的,而是一个模型:
image

Root部件可以改为透明,最后和你的模型接合起来就行了,就像下图一样:
image

把宠物模型和Root接合就行了!

宠物跟随这是我最近在做的游戏《空岛冒险者》写到的功能,虽然将大更新内容还没发布,但是宠物跟随还是有必要给部分萌新学一学的!

相关知识

用代码做简单的宠物跟随功能,小宠物是如何一直跟随玩家的
Unity宠物跟随
unity宠物跟随移动控制资源
方舟生存进化宠物停止跟随玩家方法介绍
一起来捉妖宠物如何跟随 及怎么取消跟随
unity宠物跟随移动控制
长安幻想怎么关闭宠物跟随 长安幻想关闭宠物跟随方法
时空猎人宠物怎么跟随
剑网3指尖江湖宠物跟随怎么开启 宠物跟随开启方法攻略
原神如何获得跟随宠物

网址: 用代码做简单的宠物跟随功能,小宠物是如何一直跟随玩家的 https://www.mcbbbk.com/newsview455432.html

所属分类:萌宠日常
上一篇: 长安幻想怎么关闭宠物跟随 长安幻
下一篇: 迷你世界怎么让宠物跟随

推荐分享