Torus 3D

Actionscript:
  1. stage.frameRate = 30;
  2. const TWO_PI:Number = Math.PI * 2;
  3. var centerX:Number = 200;
  4. var centerY:Number = 200;
  5. var p:Array = new Array();
  6. var zpos:Number;
  7. var xpos:Number;
  8. var ypos:Number;
  9. var depth:Number;
  10. var canvas:BitmapData = new BitmapData(400,400,true,0xFF000000);
  11. addChild(new Bitmap(canvas));
  12.  
  13. var dy:Number = 0
  14. var dx:Number = 0;
  15.  
  16. addEventListener(Event.ENTER_FRAME, onLoop);
  17. function onLoop(evt:Event):void {
  18.     canvas.fillRect(canvas.rect, 0xFF000000);
  19.      
  20.      dx += (mouseX / 100 - dx)/12;
  21.      dy += (mouseY / 100 - dy)/12;
  22.      var xp:Number, yp:Number, zp:Number;
  23.      
  24.      canvas.lock();
  25.      for (var a:Number =0; a <TWO_PI; a+=.08){
  26.           for (var b:Number =0; b <TWO_PI; b+=.08){
  27.               xp = (70 + 40 * Math.cos(a)) * Math.cos(b) ;
  28.               yp = (70 + 40 * Math.cos(a)) * Math.sin(b);
  29.               zp =  40 * Math.sin(a);
  30.               calc3D(xp, yp, zp, dx, dy);
  31.               convert3D();
  32.               canvas.setPixel(p[0], p[1], 0xFFFFFF);
  33.           }
  34.      }
  35.      canvas.unlock();
  36. }
  37. function calc3D(px:Number, py:Number, pz:Number, rotX:Number=0, rotY:Number=0):void {
  38.     // I first learned this from code by Andries Odendaal - www.wireframe.co.za
  39.     zpos=pz*Math.cos(rotX)-px*Math.sin(rotX) ;
  40.     xpos=pz*Math.sin(rotX)+px*Math.cos(rotX) ;
  41.     ypos=py*Math.cos(rotY)-zpos*Math.sin(rotY) ;
  42.     zpos=py*Math.sin(rotY)+zpos*Math.cos(rotY);
  43. }
  44. function convert3D():void {
  45.     depth = 1/((zpos/200)+1);
  46.     p[0] =  xpos * depth + centerX;
  47.     p[1] =  ypos * depth + centerY;
  48. }

This code draws a rotating 3D torus using setPixel().

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

Post a Comment

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

*
*