Unity3D 實現類似“紀念碑谷”扭曲物體的效果
阿新 • • 發佈:2019-01-28
using UnityEngine; using System.Collections; using System; public class TwistScript : MonoBehaviour { public float twist = 1.0f; public float inputSensitivity = 1.5f; private Vector3[] baseVertices; private Vector3[] baseNormals; private Vector3 new_pos; // Update is called once per frame void Update () { twist += Input.GetAxis("Horizontal") * inputSensitivity * Time.deltaTime; //限制扭曲範圍 if (twist < -2) { twist = -2; } if (twist > 2) { twist = 2; } Mesh mesh = GetComponent<MeshFilter>().mesh; if (baseVertices == null) { baseVertices = mesh.vertices; } if (baseNormals == null) { baseNormals = mesh.normals; } Vector3[] vertices = new Vector3[baseVertices.Length]; Vector3[] normals = new Vector3[baseNormals.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = DoTwist(baseVertices[i], baseVertices[i].y * twist); normals[i] = DoTwist(baseNormals[i], baseVertices[i].y * twist); } mesh.vertices = vertices; mesh.normals = vertices; mesh.RecalculateNormals(); mesh.RecalculateBounds(); } //產生扭曲 private Vector3 DoTwist(Vector3 pos, float t) { float st = Mathf.Sin(t); float ct = Mathf.Cos(t); new_pos = Vector3.zero; new_pos.x = pos.x * ct - pos.z * st; new_pos.z = pos.x * st + pos.z * ct; new_pos.y = pos.y; return new_pos; } }