萝卜说 - 罗布乐思 - 口袋核心

查看: 958|回复: 0

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

[复制链接]

0

收听

0

听众

30

帖子

正式用户

Rank: 1

萝卜币
57
发表于 2021-5-31 13:58:02 | 显示全部楼层 |阅读模式
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") then
        AlignOrientation = Instance.new("AlignOrientation",root)
else
        AlignOrientation = root.AlignOrientation
end
if not root:FindFirstChild("Attachment") then
        Attachment = Instance.new("Attachment",root)
else
        Attachment = root.Attachment
end
if not root:FindFirstChild("BodyPosition") then
        BodyPosition = Instance.new("BodyPosition",root)
else
        BodyPosition = root.BodyPosition
end
--检测到玩家就跟随
RunService.Stepped:Connect(function()
        avatar = pet.Parent
        local hroot = avatar:FindFirstChild("HumanoidRootPart")
        local humanoid = avatar:FindFirstChild("Humanoid")
        if avatar and hroot and humanoid then--判断父级对象也就是角色存在
                BodyPosition.P = 5000
                local 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 = Attachment
                AlignOrientation.Attachment1 = avatar.HumanoidRootPart.RootRigAttachment
                BodyPosition.Position = tarpos
        end
end)
4、最后一步骤来了,运行游戏,然后切换成当前服务器:


把宠物拖到角色下:




换回当前客户端:


看看效果!


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


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


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

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋| |京公网安备11010502045240号

Copyright © 2001-2013 Comsenz Inc.   All Rights Reserved.

Powered by Discuz! X3.4  备案:京ICP备2021013067号-2

快速回复 返回顶部 返回列表