现有一Live2D模型和一个Unity ParticleSystem渲染的粒子特效,需要获取Live2D模型特定Drawable的实时位置,让Unity的特效跟踪这个Drawable渲染。
试了传统的 drawable.gameObject.transform.position ,无效,挂上drawable只能显示整个模型的位置,而且不会变。查看Live2D模型结构发现Drawable都是由MeshRenderer渲染的,可能要获取Mesh的位置才行,又尝试mesh = drawable.GetComponent<MeshFilter>().mesh;,然后用mesh.bounds.center的方法获取mesh的中心点,这次返回值确实是对应Drawable的mesh位置,但依然不能随模型动画变化。
最后从Live2D Cubism SDK 的Unity pkg源码中找到了获取方法。在CubismRaycaster组件中,需要通过判断鼠标射线和Drawable的位置关系,显然需要知道Drawable的实时位置,Live2D Cubism的解决方法是:
raycastable = candidate.GetComponent<CubismRenderer>();
// candidate是挂了raycastable的某个Drawable
bounds = raycastable.Mesh.bounds;
可以看到,获取的是CubismRenderer下的Mesh,而不是Mesh Filter的Mesh。测试了一下,确实可行。
完整代码实现:
using Live2D.Cubism.Rendering;
using UnityEngine;
public class Test : MonoBehaviour
{
public GameObject targetDrawable;
public GameObject targetEffect;
private Mesh mesh;
void Start()
{
mesh = targetDrawable.GetComponent<CubismRenderer>().Mesh;
}
void LateUpdate()
{
Vector3 drawablePosition = mesh.bounds.center;
// Debug.Log($"The center of target drawable: {drawablePosition}");
targetEffect.transform.position = drawablePosition;
}
}