-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMeshDeformer.cs
More file actions
60 lines (50 loc) · 1.82 KB
/
Copy pathMeshDeformer.cs
File metadata and controls
60 lines (50 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshCollider))]
public class MeshDeformer : MonoBehaviour
{
[Header("Deformation Physics")]
public float springForce = 20f;
public float damping = 5f;
private Mesh deformingMesh;
private Vector3[] originalVertices;
private Vector3[] displacedVertices;
void Start()
{
deformingMesh = GetComponent<MeshFilter>().mesh;
originalVertices = deformingMesh.vertices;
displacedVertices = new Vector3[originalVertices.Length];
for (int i = 0; i < originalVertices.Length; i++)
{
displacedVertices[i] = originalVertices[i];
}
}
public void AddDeformation(Vector3 worldPoint, float radius, float force)
{
Vector3 localPoint = transform.InverseTransformPoint(worldPoint);
for (int i = 0; i < displacedVertices.Length; i++)
{
AddForceToVertex(i, localPoint, radius, force);
}
UpdateVertexPositions();
}
void AddForceToVertex(int i, Vector3 point, float radius, float force)
{
Vector3 pointToVertex = displacedVertices[i] - point;
float distance = pointToVertex.magnitude;
if (distance < radius)
{
float attenuation = force / (1f + pointToVertex.sqrMagnitude);
float velocity = attenuation * Time.deltaTime;
Vector3 velocityVector = pointToVertex.normalized * velocity;
displacedVertices[i] += velocityVector;
}
}
void UpdateVertexPositions()
{
deformingMesh.vertices = displacedVertices;
deformingMesh.RecalculateNormals();
deformingMesh.RecalculateBounds();
GetComponent<MeshCollider>().sharedMesh = deformingMesh;
}
}