Runtime crater mesh deformations

Since I’m already deforming my planets at runtime using a noise map, it made sense to include the ability to add craters to the planets when a large event occurs (landing or blasting off for example).

landingcrater

It’s not entirely ideal but my system seems to work alright – the biggest issue is that I use the deformed surfaces for my mesh collider as well so I need to be careful how much I warp the surface or it might cause issues with character mobility.

 

Here’s the gist of it:

float craterSize = 5.0f;

Mesh mesh = GetComponent<MeshFilter>().mesh;
List<Vector3> vertices = mesh.vertices.ToList();
for (int i = 0; i < vertices.Count; i++) 
{
     vertices[i] = transform.TransformPoint(vertices[i]);
     float distFromCrater =  Vector3.Distance(vertices[i], craterOrigin);
     if (distFromCrater < craterSize)
     {
          Vector3 dirFromCrater = (craterOrigin  vertices[i]).normalized;
          vertices[i] = vertices[i]  dirFromCrater * (craterSize  distFromCrater)/2.0f;   
     }
     vertices[i] = transform.InverseTransformPoint(vertices[i]);
}
mesh.SetVertices(vertices);
mesh.RecalculateNormals();

 

So once I have an array of all the vertices I convert each one into world space (using transform.TransformPoint()) and I can check how close each vertex is from the source of the crater explosion. If a vertex is within range of the crater explosion then I move it back away from the crater origin based on its proximity – so it’s most impacted at the center and becomes gentle towards the edges. Then I convert the vertices back to local space using transform.InverseTransformPoint() and I can assign my modified vertex array back to the mesh. It’s also very important to recalculate the normals.

That’s essentially all there is to it. I use a particle system using rock models to represent the earth that has been displaced and mask the sudden model change in the explosion effects as well. I’ll likely need to limit the number of craters that can be made in a single area to avoid the terrain being completely distorted since it’s definitely possible to start making things weird with enough repeated deformations.