实现
1.在目标spine动画下新建一个空物体。
2.给空物体添加BoneFollwer脚本(sprite动画添加BoneFollwer, ui动画添加BoneFollowerGraphic)。此时spine动画上会显示出骨骼节点。
3.选择需要挂载的目标骨骼节点。此时运行会发现挂有该脚本的物体会跟随选中的骨骼节点移动。 4.给挂有脚本的物体下附加目标即可完成跟随。
写个管理器方便使用。
using Spine.Unity;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoneFollowerMgr : MonoBehaviour
{
public static BoneFollowerMgr instance;
//存储spine和骨骼对象
Dictionary spineMap = new Dictionary();
void Awake()
{
instance = this;
}
//检查spine中是否存在该骨骼
public bool HasBone(string boneName, SkeletonRenderer spine)
{
return spine.Skeleton.FindBone(boneName) != null;
}
//获取并创建传入骨骼名称的BoneFollower
public BoneFollower GetBoneFollower(SkeletonRenderer spine,string boneName)
{
if (!spineMap.ContainsKey(spine))
{
spine.Initialize(true);
}
else
{
if (spineMap[spine].ContainsKey(boneName))
return spineMap[spine][boneName];
}
if (HasBone(boneName,spine))
{
GameObject o = new GameObject(boneName);
o.transform.SetParent(spine.transform, false);
BoneFollower follow = o.AddComponent();
follow.boneName = boneName;
follow.SkeletonRenderer = spine;
Dictionary boneMap;
if (spineMap.ContainsKey(spine))
{
if(spineMap[spine].Count > 0)
{
boneMap = spineMap[spine];
}
else
{
boneMap = new Dictionary();
}
}
else
{
boneMap = new Dictionary();
spineMap.Add(spine,boneMap);
}
boneMap.Add(boneName, follow);
spineMap[spine] = boneMap;
return follow;
}
Debug.LogError("Do not have this bone!");
return null;
}
//移除缓存中的指定spine
public void RemoveSpine(SkeletonRenderer spine)
{
if (spineMap.ContainsKey(spine))
{
spineMap.Remove(spine);
}
else
{
Debug.LogError("Do not have this spine!");
}
}
public void RemoveAllSpine()
{
spineMap.Clear();
}
}
测试类
using Spine.Unity;
using UnityEngine;
public class TestBoneFollower : MonoBehaviour
{
public Sprite sp;
private void Start()
{
var follower = BoneFollowerMgr.instance.GetBoneFollower(GetComponent(),"spear3");
var o = new GameObject("o", typeof(SpriteRenderer));
o.transform.SetParent(follower.transform, false);
o.GetComponent().sprite = sp;
o.transform.localScale = Vector3.one;
o.transform.position = Vector3.zero;
}
}