- Home /
Question by
steveinshort · Jun 26, 2018 at 03:26 PM ·
animationmeshdeformation
Is it possible to deform an animated mesh?
I'm importing a mesh from Maya with animation into Unity. I would like to deform the animated mesh in Unity, in real time. I was able to get this to work modifying a tutorial for my needs, see the code below. I can't seem to get it to work on the animated mesh though. I'm guessing this is because in the order of operations it's deforming the mesh, then animating it. Any suggestions or is this impossible.
Thanks!
using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(MeshFilter))] public class MeshDeformer : MonoBehaviour {
Mesh deformingMesh;
Vector3[] originalVertices, displacedVertices;
Vector3[] vertexVelocities;
public float springForce = 20f;
public float damping = 5f;
float uniformScale = 1f;
// Use this for initialization
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];
}
vertexVelocities = new Vector3[originalVertices.Length];
}
// Update is called once per frame
void LateUpdate () {
uniformScale = transform.localScale.x;
for (int i = 0; i < displacedVertices.Length; i++) {
UpdateVertex(i);
}
deformingMesh.vertices = displacedVertices;
deformingMesh.RecalculateNormals();
}
void UpdateVertex (int i) {
Vector3 velocity = vertexVelocities[i];
Vector3 displacement = displacedVertices[i] - originalVertices[i];
displacement *= uniformScale;
velocity -= displacement * springForce * Time.deltaTime;
velocity *= 1f - damping * Time.deltaTime;
vertexVelocities[i] = velocity;
displacedVertices[i] += velocity * (Time.deltaTime / uniformScale);
}
public void AddDeformingForce (Vector3 point, float force) {
Debug.DrawLine(Camera.main.transform.position, point);
point = transform.InverseTransformPoint(point);
for (int i = 0; i < displacedVertices.Length; i++) {
AddForceToVertex(i, point, force);
}
}
void AddForceToVertex (int i, Vector3 point, float force) {
Vector3 pointToVertex = displacedVertices[i] - point;
pointToVertex *= uniformScale;
float attenuatedForce = force / (1f + pointToVertex.sqrMagnitude);
float velocity = attenuatedForce * Time.deltaTime;
vertexVelocities[i] += pointToVertex.normalized * velocity;
}
}
Comment
Your answer
Follow this Question
Related Questions
Weird animation problems? 1 Answer
Mesh deformation/wobbling 1 Answer
Make mesh collider constantly change 1 Answer