Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- // visually scale this object in global space around some arbitrary vector
- public class SquashA : MonoBehaviour
- {
- // A reference mesh that will never be deformed
- public Transform MeshObject;
- Mesh origMesh;
- Vector3[] origVerts;
- // copy that mesh to this mesh but deform it
- Mesh mesh;
- Vector3[] verts;
- // The direction along which the stretch/squash is performed...
- public Vector3 squashAxis = Vector3.up;
- // ...and the scaling along that axis.
- public float scale = 0.5f;
- void Start()
- {
- origMesh = MeshObject.GetComponent<MeshFilter>().mesh;
- mesh = GetComponent<MeshFilter>().mesh;
- }
- void Update()
- {
- // This mesh follows the invisible reference mesh (which is not deformed)
- transform.position = MeshObject.position;
- transform.rotation = MeshObject.rotation;
- origVerts = origMesh.vertices;
- verts = origMesh.vertices;
- LocalToWorld();
- // Create a new local coordinate space where one axis is the stretch/squash direction
- Vector3 r = squashAxis;
- Vector3 g = Vector3.zero;
- Vector3 b = Vector3.zero;
- Vector3.OrthoNormalize(ref r, ref g, ref b);
- DrawAxes(r, g, b);
- //A matrix transforms points into new coordinate space.
- Matrix4x4 mat = new Matrix4x4();
- mat.SetRow(0, r);
- mat.SetRow(1, g);
- mat.SetRow(2, b);
- mat.SetRow(3, new Vector4(0, 0, 0, 1));
- Matrix4x4 inv = mat.inverse;
- for (int i = 0; i < origVerts.Length; i++)
- {
- // Convert the original unaltered vertex to the new coordinate space.
- Vector3 vert = mat.MultiplyPoint3x4(origVerts[i]);
- // Change the vertex's position in the new space.
- vert.x *= scale;
- // Convert it back to the usual XYZ space.
- verts[i] = inv.MultiplyPoint3x4(vert);
- }
- // Set the updated vertex array.
- mesh.vertices = verts;
- // The normals have probably changed, so let Unity update them.
- mesh.RecalculateNormals();
- }
- void LocalToWorld()
- {
- Matrix4x4 localToWorld = MeshObject.localToWorldMatrix;
- for (int i = 0; i < origVerts.Length; ++i)
- {
- Vector3 world_v = localToWorld.MultiplyPoint3x4(origVerts[i]);
- origVerts[i] = world_v;
- Debug.DrawRay(world_v, Vector3.up * 0.01f, Color.magenta, 0.001f);
- }
- }
- void DrawAxes(Vector3 R, Vector3 B, Vector3 G)
- {
- Debug.DrawRay(transform.position, R, Color.red, 0.05f);
- Debug.DrawRay(transform.position, G, Color.green, 0.05f);
- Debug.DrawRay(transform.position, B, Color.blue, 0.05f);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement