更改网格顶点的Vector3时发生奇怪的变形

时间:2015-05-06 12:25:35

标签: unity3d unityscript

当我试图使某些网格变形时,我的情况很奇怪。

我有两个物体的场景 - 较小的圆柱体(变形器)和较大的圆柱体(可变形)。

两个对象都有C#脚本:

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

public class deformer : MonoBehaviour
{

    bool clicked = false;
    public float speed = 2f;
    public Mesh mesh;
    public Vector3[] verts;
    public float maxDistance;
    public GameObject explosion;

    void Start ()
    {
        mesh = this.GetComponent<MeshFilter> ().mesh;
        verts = mesh.vertices;
        this.GetComponent<MeshFilter> ().mesh = mesh;
    }

    void OnCollisionEnter (Collision other)
    {
        Debug.Log ("Collided with " + other.gameObject.name);
        if (other.gameObject.GetComponent<deformable> () != null) {
            Vector3 colPosition = transform.InverseTransformPoint (other.contacts [0].point);
            movePoints (other.gameObject);
        }
    }

    public void movePoints (GameObject other)
    {

        print ("entering movePoints");
        Vector3[] otherVerts = other.GetComponent<deformable> ().verts;
        float distance;
        for (int i=0; i<otherVerts.Length; i+=1) {
//          print(i);

            distance = Vector3.Distance ((GetComponent<Rigidbody> ().position), other.transform.TransformPoint (otherVerts [i]));

            if (distance <= maxDistance) {

                print (otherVerts [i]);                     
                otherVerts [i] = new Vector3 (otherVerts [i].x, otherVerts [i].y + (1 / distance), otherVerts [i].z);

            }
        }
        other.GetComponent<deformable> ().UpdateMesh (otherVerts);
    }

}

using UnityEngine;
using System.Collections;

public class deformable : MonoBehaviour
{

    public Mesh mesh;
    public Vector3[] verts;
    public Mesh oldMesh;

    void Start ()
    {
        if (mesh == null) {
            oldMesh = mesh = this.GetComponent<MeshFilter> ().mesh;
        }
        verts = mesh.vertices;
        this.GetComponent<MeshFilter> ().mesh = mesh;
    }

    public void UpdateMesh ()
    {
        mesh.vertices = verts;
        this.GetComponent<MeshFilter> ().mesh.vertices = mesh.vertices;
    }

    public void UpdateMesh (Vector3[] points)
    {
        mesh.vertices = points;
        this.GetComponent<MeshFilter> ().mesh.vertices = mesh.vertices;
        this.GetComponent<MeshCollider> ().sharedMesh = null;
        this.GetComponent<MeshCollider> ().sharedMesh = mesh;
    }

    void OnApplicationQuit ()
    {
        this.GetComponent<MeshFilter> ().mesh.vertices = oldMesh.vertices;
        this.GetComponent<MeshCollider> ().sharedMesh = null;
        this.GetComponent<MeshCollider> ().sharedMesh = oldMesh;
    }

}

结果,当变形器命中可变形时,不会对可变形对象进行任何更改:

初始场景: enter image description here

点击场景: enter image description here

在击中场景之后 - 这里可变形必须改变: enter image description here

在这种情况下最奇怪的是,脚本的哪些变化并未应用于游戏场景,而是应用于Unity编辑器的场景! enter image description here

为什么更改不会应用于游戏场景,而是应用于编辑器场景?

0 个答案:

没有答案