Procedural 3D (5,000 pixel sphere)

October 2nd, 2008

Just playing with some procedural 3D stuff.... I was actually working in Papervision today and that inspired me to dig up my old 3d functions and start playing...


move mouse to lower right corner to see sphere // move to upper left to see a mini-galaxy

This movie requires Flash Player 9

The code is pretty simple, I use a big bitmap and then scale it down to create anti-aliased pixels.... the core functions are calc3D() and convert3D()....

Actionscript:
  1. var centerX:Number = 500;
  2. var centerY:Number = 500;
  3. var p:Array = new Array();
  4. var zpos:Number;
  5. var xpos:Number;
  6. var ypos:Number;
  7. var depth:Number;
  8.  
  9. var canvas:BitmapData = new BitmapData(1000,1000,true,0xFF000000);
  10. var frame:Bitmap = new Bitmap(canvas, "auto", true);
  11. frame.scaleX = frame.scaleY = .5;
  12. addChild(frame);
  13.  
  14. var rx:Array = new Array();
  15. var ry:Array = new Array();
  16. for (var i:int = 0; i<5000; i++) {
  17.     rx.push(Math.random()*(Math.PI*2));
  18.     ry.push(Math.random()*(Math.PI*2));
  19. }
  20. var inc:Number = 0;
  21. var dx:Number=0;
  22. var dy:Number=0;
  23. addEventListener(Event.ENTER_FRAME, onLoop);
  24. function onLoop(evt:Event):void {
  25.    
  26.     canvas.fillRect(canvas.rect, 0xFF000000);
  27.     inc+=.05;
  28.     dx+= (mouseX/50 - dx)/12;
  29.     dy += (mouseY/50 - dy)/12
  30.     for (var i:int = 0; i<5000; i++) {
  31.         // local space of the sphere
  32.         calc3D(200,0,0,rx[i]  , ry[i]  +inc);
  33.         xpos+=50;
  34.         // final space for the sphere
  35.         calc3D(xpos, ypos, zpos,dx, dy);
  36.         convert3D();
  37.         canvas.setPixel(p[0], p[1], 0xFFFFFF);
  38.     }
  39. }
  40.  
  41. function calc3D(px:Number, py:Number, pz:Number, rotX:Number=0, rotY:Number=0):void {
  42.     // I first learned this from code by Andries Odendaal - www.wireframe.co.za
  43.     zpos=(pz*Math.cos(rotX))-(px*Math.sin(rotX)) ;
  44.     xpos=(pz*Math.sin(rotX))+(px*Math.cos(rotX)) ;
  45.     ypos=(py*Math.cos(rotY))-(zpos*Math.sin(rotY)) ;
  46.     zpos=(py*Math.sin(rotY))+(zpos*Math.cos(rotY));
  47. }
  48. function convert3D():void {
  49.     depth = 1/((zpos/mouseY)+1);
  50.     p[0] = (xpos * depth) + centerX;
  51.     p[1] = (ypos * depth) + centerY;
  52. }

One Response to “Procedural 3D (5,000 pixel sphere)”

  1. subblue Says:

    Had great fun playing around with this!

Leave a Reply