Unity 使用 EzySlice 实现模型切割
老规矩,直接上代码:
注意:脚本搭载和需要的材质球以及切割数组填充
EzySlice 多边形顺序切割
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EzySlice;
public class SplitterModel_ZH : MonoBehaviour
{
//切割预制体材质
public Material _NewMaterial;
//被切割预制体数组
public List<GameObject> _ListGamPreFab;
//调用切割模型数组 序号
private int _ListInt = 0;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(SlicedModel());
}
}
public IEnumerator SlicedModel()
{
if (_ListGamPreFab != null)
{
//创建忽略切割对象
Collider[] _Colliders = Physics.OverlapBox(_ListGamPreFab[_ListInt].transform.position, new Vector3(4, 0.00005f, 4), _ListGamPreFab[_ListInt].transform.rotation, ~LayerMask.GetMask("Solid"));
foreach (var item in _Colliders)
{
//销毁当前被切割物体
Destroy(item.gameObject);
//切割出现的物体
SlicedHull _SlicedHull = item.gameObject.Slice(_ListGamPreFab[_ListInt].transform.position, _ListGamPreFab[_ListInt].transform.up);
if (_SlicedHull != null)
{
//切割下半部分部分 物体
GameObject _Lower = _SlicedHull.CreateLowerHull(item.gameObject, _NewMaterial);
//切割上半部分部分 物体
GameObject _Upper = _SlicedHull.CreateUpperHull(item.gameObject, _NewMaterial);
//销毁切割形成的上半部分
Destroy(_Lower);
//添加网格组件
_Upper.AddComponent<MeshCollider>();
//当前切割物体消失(可扩展)
_ListGamPreFab[_ListInt].gameObject.SetActive(false);
#region 弃用
//for (int i = 0; i < _objs.Length; i++)
//{
// _objs[i].AddComponent<Rigidbody>();
// _objs[i].AddComponent<MeshCollider>().convex = true;
// //奇 偶 判断 如果是奇数
// if ((i & 1) != 0)
// {
// }
//}
#endregion
}
}
}
_ListInt++;
//延迟执行
yield return new WaitForSeconds(0.5f);
//判断数组大小
if (_ListInt == _ListGamPreFab.Count)
{
//停止协程
StopCoroutine(SlicedModel());
}
else
{
StartCoroutine(SlicedModel());
}
}
}
补充一点:当前切割数组可扩展,可以使用 LineRender 绘画实现自定义,只不过我没时间去写。
如果有那位大神写了请帮忙踢我一下,哈哈哈。
初始状态:
脚本搭载情况:
最终效果:
暂时先这样吧,如果有时间的话就会更新,如果实在看不明白就留言,看到我会回复的。
路长远兮,与君共勉。