
A few weeks back I got thinking. Would it be possible to have a terrain within Unity deform in real-time? For example if an explosion went off, could it blow a hole in the terrain? I decided this would be a good project to learn the more ‘advanced’ features of Terrains within Unity.
It ended up being more challenging than I predicted, as it was difficult to get the framerate to remain stable while performing these operation. Using a few tricks I ended up getting it to work exactly as I had hoped.
The demo works like this. A script randomly spawns ’shells’ that fall quickly to the ground. Each shell has an onTrigger collider attached to it. If this collides with a terrain that has a TerrainDeformer component, the shell tells that component its location and the force of the explosion. The shell then instantiate an explosion (supplied by Ben Throop great Detonator framework), and removes itself.
The TerrainDeformer script then translates that position to the correct location relative to it’s terrain and modifies both the heightmap (terrain height) and the alphamap (terrain texture). A bit of math is used to find all the heightmap and alphamap position within the area of the impact circle.
The texture which is used to re-texture the impact area is chosen from the list of terrain textures based on the numerical index value passed into the script (Terrain Deformation Texture Num). In this example it is set to one, so it will re-texture with the second texture in the list.
When creating your own terrains it is necessary for the height of the terrain to be higher than 0 meters so craters can be formed. I recommend a depth of at least 3 meters. This can done by setting the terrain height to something higher than 3 meters, then clicking Terrain->Flatten Heightmap and entering 3 meters.
For performance reasons it is important to keep your terrain size small and more importantly keep your Heightmap Resolution low. In this example it is set to 33.
The current version does have limitations like lack of terrain edge detection and support for multiple terrains. This example is more of proof of concept to show that not only can it be done, but done without much of a performance hit.
Thanks to Calin for creating the dirt texture.
To check out the demo click here.
To get the source (unitypackage) click here.
Source Requirements: Unity 2.6 and the Detonator Framework.