Isometric Voxels

Actionscript:
  1. // isometric conversion
  2. var centerX:Number=stage.stageWidth/2;
  3. var centerY:Number=stage.stageHeight/2;
  4. var theta:Number=Math.PI/4;// 45 degrees;
  5. var cosX:Number=Math.cos(theta);
  6. var sinX:Number=Math.sin(theta);
  7. var pnt:Point = new Point();
  8. function iso3D(x:Number, y:Number, z:Number):Point {
  9.     pnt.x = centerX + (x-z) *  cosX
  10.     pnt.y = centerY -  (x+z) * 0.5 * sinX - y;
  11.     return pnt;
  12. }
  13. // example:
  14. var canvas:BitmapData=new BitmapData(stage.stageWidth,stage.stageHeight,true,0xFF000000);
  15. addChild(new Bitmap(canvas,"auto",true));
  16. var size:int=100;
  17. var hs:int=size / 2;
  18. var pen:Point = new Point();
  19. var vect:Vector3D = new Vector3D();
  20. // draw a few shapes with offset:
  21. for (var dist:int = 10; dist <= 80; dist *= 2) {
  22.     // voxel space:
  23.     for (var i:int = 0; i<size; i++) {
  24.         for (var j:int = 0; j<size; j++) {
  25.             for (var k:int = 0; k<size; k++) {
  26.                 vect.x=j-hs;
  27.                 vect.y=i-hs;
  28.                 vect.z=k-hs;
  29.                 pen = iso3D(vect.x,vect.y,vect.z);
  30.                 if (Math.sqrt((vect.x * vect.x) + (vect.y * vect.y) + (vect.z * vect.z)) <dist) {
  31.                     // using Vector3D.distance() is very slow compared to above
  32.                     // a few types of coloring:
  33.                     var xp:Number = pen.x + (dist <<2) - 200;
  34.                     canvas.setPixel(xp, pen.y-100, (i <<16 | j <<8 | k) <<1);
  35.                     canvas.setPixel(xp, pen.y+100, (k <<16 | k <<8 | k+j)  );
  36.                 }
  37.             }
  38.         }
  39.     }
  40. }

The above will draw this:

You can read more about voxels here.

This isn't the speediest way to do voxels (especially if you want to animate). This was just the first thing that came to mind.

This entry was posted in 3D, BitmapData, color, pixel manipulation, setPixel and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted February 25, 2011 at 6:51 am | Permalink

    Hi Zevan,

    I found your code and traslate to :r4 only for fun, the result is in

    http://code.google.com/p/reda4/source/browse/trunk/r4/Apps/simplevoxel.txt

    I hope you not angry :)

    Bye
    Pablo

  2. Posted February 25, 2011 at 8:25 am | Permalink

    Hey Pablo. Why would I be angry…. that’s awesome :) nice work.

  3. Milan
    Posted April 29, 2011 at 11:06 pm | Permalink

    Hey will u please explain why you write this line i cant understand that
      var xp:Number = pen.x + (dist <<2) - 200;

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*