Unity Spine碰撞框形状无法跟随改变
最近使用Spine的时候,Spine在动画编辑中修改了碰撞框形状,导入到unity中使用BoundingBoxFollower脚本,发现在Spine碰撞框形状修改的时候,不会自动跟随更新。
后来到Spine官方论坛查到资料才发现:
大概意思就是Unity的PolygonCollider2D设计初衷不支持动态改变形状,如果改变的话将会耗费大量的计算和意想不到的错误。如果非要修改的话,Spine sdk的数据是正常的,可以自己进行变更。但是没有说如何变更。查看了源代码,尝试出来了,
在BoundingBoxFollower中添加如下代码可以刷新碰撞块形状:
[ContextMenu("UpdateBoundingBox")]
void UpdateBoundingBox(){
var worldVerts = new float[CurrentAttachment.Vertices.Length];
CurrentAttachment.ComputeWorldVertices(slot, worldVerts);
int worldVertsLength = worldVerts.Length;
int bufferTargetSize = worldVertsLength >> 1;
Vector2[] buffer = new Vector2[bufferTargetSize];
var floats = worldVerts;
Vector3 vert = Vector3.zero;
for (int i = 0, n = worldVertsLength >> 1; i < n; i++) {
int j = i * 2;
vert.x = floats[j];
vert.y = floats[j + 1];
vert.z = 0;
float aaa = vert.x;
float bbb = vert.y;
Slot.Bone.WorldToLocal (aaa, bbb, out aaa, out bbb);
vert.x = aaa;
vert.y = bbb;
buffer[i] = vert;
}
CurrentCollider.SetPath (0, buffer);
}