Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using BezierCurveZ;
- using System.Collections;
- using System.Collections.Generic;
- using Unity.VisualScripting;
- using UnityEditor;
- using UnityEngine;
- using Utility;
- [ExecuteAlways]
- [SelectionBase]
- public class MeshBender : MonoBehaviour
- {
- public Mesh originalMesh;
- public float originalLength = 1f;
- public MeshFilter meshFilter;
- [Tooltip("Only first segment will be accounted")]
- [ContextMenuItem("UpdateMesh", "UpdateMesh")]
- public Curve curve;
- private void OnEnable()
- {
- if (originalMesh.IsNullOrDestroyed() && meshFilter) originalMesh = meshFilter.sharedMesh;
- UpdateMesh();
- }
- [ContextMenu("UpdateMesh")]
- public void UpdateMesh()
- {
- var mesh = meshFilter.sharedMesh;
- if (mesh == originalMesh)
- mesh = originalMesh.Copy();
- Transform mfTransform = meshFilter.transform;
- var thisToMeshMatrix = mfTransform.worldToLocalMatrix * transform.localToWorldMatrix;
- var meshToThisMatrix = transform.worldToLocalMatrix * mfTransform.localToWorldMatrix;
- var verts = originalMesh.vertices;
- for (int i = 0; i < verts.Length; i++)
- {
- var v = meshToThisMatrix.MultiplyPoint3x4(verts[i]);
- var t = Mathf.Clamp01(v.z / originalLength);
- var point = curve.VertexData.GetPointFromTime(t);
- var vRelToPoint = v - new Vector3(0, 0, t * originalLength);
- verts[i] = thisToMeshMatrix.MultiplyPoint3x4(point.Position + point.Rotation * vRelToPoint);
- }
- mesh.vertices = verts;
- meshFilter.sharedMesh = mesh;
- }
- #if UNITY_EDITOR
- private void OnDrawGizmosSelected()
- {
- var m = Handles.matrix;
- var c = Handles.color;
- Handles.color = new Color(.3f, .3f, 1f);
- Handles.matrix = transform.localToWorldMatrix;
- var origTgt = Vector3.forward * originalLength;
- Handles.DrawAAPolyLine(Vector3.zero, origTgt);
- Handles.DrawAAPolyLine(Vector3.right * -.5f, Vector3.right * .5f);
- Handles.DrawAAPolyLine(Vector3.forward * originalLength + Vector3.right * -.5f, Vector3.forward * originalLength + Vector3.right * .5f);
- Handles.color = new Color(.3f, 1f, .3f);
- var tgt = curve.Points[curve.GetPointIndex(1)];
- Handles.DrawAAPolyLine(Vector3.right * -.5f, Vector3.right * .5f);
- Handles.DrawAAPolyLine(tgt + tgt.right * -.5f, tgt + tgt.right * .5f);
- Handles.DrawAAPolyLine(curve.VertexDataPoints);
- Handles.color = c;
- Handles.matrix = m;
- }
- #endif
- }
Advertisement
Comments
-
- Usings are not correct:
- using BezierCurveZ;
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- using UnityEngine;
- using Utility;
Add Comment
Please, Sign In to add comment
Advertisement