Real-Time Mesh Deforming problem

Hey everyone. I want to know if it’s possible to make such a Real-time mesh Deformation System like I am thinking to do. My way to do this would be a OnCollisionEnter in the Mesh to get the Contact Point with the collisor and pass this Vector3 to a function wich is a for loop that check de Distance of each vertice to the contact Point and if it’s less than like 20.0F the vertice go down in the y axis with the strength of CollisorMass/DistanceToContactPoint.
I apply this way of think in a script but the deformation is not occurring in the Contact Point and sometimes the mesh not even deform. Here are the two necessary voids:

void Deform(Vector3 colPos, float colMass) {
	
	Vector3 newColPos = new Vector3(colPos.x, 0, colPos.z);
	 Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
		Vector3[] vertices = mesh.vertices;
	for(int i = 0; i < mesh.vertexCount; i++) {
		float distance = Vector3.Distance(vertices*, newColPos);*
  •   if(distance < 20.0F) {*
    

vertices = new Vector3(vertices.x, vertices_.y, vertices*.z - (colMass/distance));*_

* }*
* }*
mesh.vertices = vertices;
* mesh.RecalculateBounds();*

* }*

* void OnCollisionEnter(Collision collider) {*

* Vector3 colPosition = collider.contacts[0].point;*
* Deform(colPosition, collider.gameObject.GetComponent().mass);*
* }*
Hope you guys can help me with this!

1 Answer

1

You must convert the contact point to object space, since the mesh.vertices is in object space.

Just substitute the following line in OnCollisionEnter:
Vector3 colPosition = renderer.worldToLocalMatrix * collider.contacts[0].point;

Now, for this to work as intended, avoid changing the gameObject’s scale. Otherwise you’ll have to change how you measure distance in object space.

The <a href="http://unity3d.com/support/documentation/ScriptReference/Renderer-worldToLocalMatrix.html">renderer matrices</a> are special matrices for shader parameters. In your usual gamelogic you should better use <a href="http://unity3d.com/support/documentation/ScriptReference/Transform-worldToLocalMatrix.html">transform.worldToLocalMatrix</a> or what would be actually easier to read: <a href="http://unity3d.com/support/documentation/ScriptReference/Transform.InverseTransformPoint.html">transform.InverseTransformPoint(collisionInfo.contacts[0].point)</a>