QQ聊天

Unity实现一个morpher/blendShape

 

using UnityEngine;
using System.Collections;

[RequireComponent (typeof (MeshFilter))]
public class BlendShape : MonoBehaviour
{
    public Mesh[] meshs;
    #if UNITY_EDITOR
        public float[] weights;
    #else
        float[] weights;
    #endif


    bool isChange = false;
    void Start () 
    {
        weights = new float[meshs.Length];
        System.Array.Clear (weights,0,weights.Length);
        GetComponent<MeshFilter> ().mesh = meshs [0];
    }


    public void SetWeight(int argIndex,float argWeight)
    {
        weights [argIndex] = (argWeight > 1 ? 1: argWeight );
        isChange = true;
    }

    void Update() 
    {
        UpdateMesh ();
    }

    void UpdateMesh()
    {
        #if UNITY_EDITOR
        #else
        if (!isChange) return;
        #endif

        Mesh mesh = GetComponent<MeshFilter>().mesh;

        Vector3[] vertices = new Vector3[meshs[0].vertices.Length];
        System.Array.Copy (meshs [0].vertices, vertices, vertices.Length);

        for (int w=1;w<weights.Length;w++)
        {
            if (weights[w] <= 0) continue;

            Vector3[] verticesT = meshs[w].vertices;
            
            int i = 0;
            while (i < vertices.Length) 
            {
                vertices[i] = vertices[i] + (verticesT[i] -  meshs[0].vertices[i]) * weights[w];
                i++;
            }
        }
        mesh.vertices = vertices;
        isChange = false;
    }
}
View Code

 

posted @ 2015-12-03 10:34  SITT  阅读(1895)  评论(0编辑  收藏  举报
QQ聊天