Unity插件 使用Ezy-Slice插件实现模型切割效果

Unity插件 使用Ezy-Slice插件实现模型切割效果_第1张图片

去网上下载Ezy-Slice插件

工具类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EzySlice;

public static class SliceTools
{
    public static T FaultoleranceGetComponent(GameObject go) where T : Component
    {
        if (go != null)
        {
            T component = go.GetComponent();
            if (component == null)
            {
                component = go.AddComponent();
            }
            return component;
        }
        return null;
    }


    public static SlicedHull SliceObject(GameObject obj, Vector3 positon, Vector3 normal,
        Material crossSectionMaterial = null)
    {
        // slice the provided object using the transforms of this object
        if (obj.GetComponent() == null)
            return null;

        return obj.Slice(positon, normal, crossSectionMaterial);
    }
}

核心类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EzySlice;

public class Slice : MonoBehaviour
{
    public Material sliceMat;

    void Start()
    {
        
    }

    void Update()
    {
        
    }

    private void OnTriggerEnter(Collider other)
    {
        GameObject source = other.gameObject;
        if (source.tag == Tag.player)
        {
            //Debug.Log(other.gameObject.tag);            
            //将Souce切割,传入的第一个参数为切割的位置(即刀片的位置),传入的第二个参数为切割面的法向量(即刀片表面的法向量)            
            SlicedHull hull = SliceTools.SliceObject(source, transform.position, transform.forward, sliceMat);
            //Debug.Log(hull);
            if (hull != null)
            {                
                //创建把source切割以后的上半部分物体
                GameObject uperHull = hull.CreateUpperHull(source, sliceMat);
                SliceObject(uperHull);
                //创建把source切割以后的下半部分物体
                GameObject lowerhull = hull.CreateLowerHull(source, sliceMat);
                SliceObject(lowerhull);
                //-----------处理原物体-------------------
                Destroy(source);
            }
        }
    }

    void SliceObject(GameObject shatteredObject)
    {
        if (shatteredObject == null)
        {
            return;
        }
        
        MeshCollider mcUper = SliceTools.FaultoleranceGetComponent(shatteredObject);
        if (mcUper != null)
        {
            mcUper.sharedMesh = shatteredObject.GetComponent().mesh;
            mcUper.convex = true;
        }

        Rigidbody rdUper = SliceTools.FaultoleranceGetComponent(shatteredObject);

        if (rdUper != null)
        {
            rdUper.useGravity = true;
            //rdUper.constraints = RigidbodyConstraints.FreezePositionZ;
            //rdUper.mass = 100;
        }

        SliceTools.FaultoleranceGetComponent(shatteredObject);

        shatteredObject.tag = Tag.player;
    }
}

Unity插件 使用Ezy-Slice插件实现模型切割效果_第2张图片

Slice是切片,切片上添加Slice脚本

Cube是模型,添加刚体组件,模型除自身材质外,还需要添加切割的材质。

 

你可能感兴趣的:(Unity插件)