1、首先,创建一个部件,命名为Root(部件一定要命名为Root)
2、随后将部件分组,命名为pet(不一定要pet,可随意命名),随后在分组下创建一个Script脚本,如下图:
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、最后一步骤来了,运行游戏,然后切换成当前服务器:
把宠物拖到角色下:
换回当前客户端:
看看效果!
运行成功了!
5、最后说明一下!为什么上面的第二步要分组?为什么不直接一个部件就行?
这样做是为了拓展需求,你的一个宠物不可能是一个部件的,而是一个模型:
Root部件可以改为透明,最后和你的模型接合起来就行了,就像下图一样:
把宠物模型和Root接合就行了!
宠物跟随这是我最近在做的游戏《空岛冒险者》写到的功能,虽然将大更新内容还没发布,但是宠物跟随还是有必要给部分萌新学一学的!