Terrain destruction w/source

I’ve noticed lately some people wondering about terrain destruction. I’ve had this idea how to do it for a while after playing “scorched earth”.

I noticed that scorched earth just uses a bunch a line to depict the terrain…which would be perfect for flash thanks to the drawing api.

Ok, what I planned was an array that contains each x value of the stage, and a corrosponding ground height for that x value…


groundArray[100] = 50;

This shows that the ground at x value 100 is 50 pixels high.

So whenever we want to change the height of the ground, we can change the values in an array, and then redraw the ground.

Ok, the redrawing is going to be a large loop, that goes through every value in the array and draws a line. Something like this…


for(i=0;i<550;i++)
 {
  groundArray* = 300;
  ground.lineStyle(2,0x000000,100);
  ground.moveTo(i,groundArray*);
  ground.lineTo(i,500);
 } 

Ook this is looping through the array, and setting it up with each line to have a height of 300. The lineTo command is telling the line to draw from the 300 to 500, which is the bottom of the screen.

And there you are, a stage full of lines. Which when changed, can look like terrain destruction.

Heres the source, just move your mouse over the black area, and you should see some movement.

It’s by no means optimized. The redraw function for example has to redraw the entire stage when only a small section is changed. Its also not very good code, but I just wanted to show how the theory works.

But the general idea is there for anybody considering a “Scorched Earth” type game.


_root.onLoad()
{
 var groundArray = new Array;
 
 _root.createEmptyMovieClip("ground",_root.getNextHighestDepth());
  
 for(i=0;i<550;i++)
 {
  groundArray* = 300;
  ground.lineStyle(2,0x000000,100);
  ground.moveTo(i,300);
  ground.lineTo(i,500);
 } 
 
 
}
_root.onEnterFrame = function()
{
 if(_root.ground.hitTest(_xmouse,_ymouse,true))
 {
  groundArray[Math.floor(_xmouse)] += 10;   
  for(i=1;i<10;i++)
  {
   groundArray[Math.floor(_xmouse)-i] -= ((Math.pow(i,2)/10)-10);  
   groundArray[Math.floor(_xmouse)+i] -= ((Math.pow(i,2)/10)-10);
  }
  
  reDraw();
 }
}
_root.onMouseMove = function()
{
 
}
_root.reDraw = function()
{
 _root.ground.removeMovieClip();
 
 _root.createEmptyMovieClip("ground",_root.getNextHighestDepth());
  
 for(i=0;i<550;i++)
 {
  ground.lineStyle(2,0x000000,100);
  ground.moveTo(i,groundArray*);
  ground.lineTo(i,500);
 }  
}