3D Shape

Actionscript:
  1. stage.frameRate = 30;
  2. var centerX:Number = 200, centerY:Number = 200, zpos:Number, xpos:Number, ypos:Number, depth:Number;
  3. var rotX:Number = 0, rotY:Number = 0, px:Number, py:Number, pz:Number;
  4. var cosx:Number, cosy:Number, sinx:Number, siny:Number;
  5.  
  6. var canvas:BitmapData = new BitmapData(400,400,true,0xFF000000);
  7. addChild(new Bitmap(canvas));
  8.  
  9. addEventListener(Event.ENTER_FRAME, onLoop);
  10.  
  11. function onLoop(evt:Event):void {
  12.     canvas.fillRect(canvas.rect, 0xFF000000);
  13.      rotX += (mouseX / 50 - rotX)/12;
  14.      rotY += (mouseY / 50 - rotY)/12;
  15.      
  16.      cosx = Math.cos(rotX);
  17.      cosy = Math.cos(rotY);
  18.      sinx = Math.sin(rotX);
  19.      siny = Math.sin(rotY);
  20.      for (var a:Number =0; a <6.28; a+=.1){
  21.           for (var b:Number =0; b <6.28; b+=.05){
  22.               px = 100 * Math.cos(a) * Math.cos(b) * Math.cos(b);
  23.               py = 100 * Math.sin(a) * Math.cos(b)
  24.               pz = 100 * Math.sin(b);
  25.               zpos= pz*cosx - px*sinx  ;
  26.               xpos= pz*sinx +px*cosx  ;
  27.               ypos= py*cosy - zpos*siny  ;
  28.               zpos= py*siny+ zpos*cosy ;
  29.               depth = 1/((zpos/340)+1);
  30.               canvas.setPixel((xpos * depth) + centerX, (ypos * depth) + centerY, 0xFFFFFF);
  31.           }
  32.      }
  33. }

Renders a rotating 3D shape.

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

4 Comments

  1. Posted November 26, 2008 at 10:19 am | Permalink

    this is pretty neat looking. when you’re writing code like this, how do you know all these random numbers like 6.28? is it through experimentation or are you finding formulas somewhere and converting them to AS?

    also, i’ve been meaning to ask you, you talk alot in your posts about your students, where do you teach? when i was in college we were doing director :( even then, though, with the little flash we did, we didn’t really do much AS, mostly timeline and simple AS stuff.

  2. Posted November 26, 2008 at 10:40 am | Permalink

    The 6.28 is a lazy way of writing (2 * Math.PI)… that’s 360 degrees in radians. For the above code I just used the equation for a sphere:

    x = r *cos(a)*cos(b)
    y = r * sin(a)*cos(b)
    z = r * sin(b)

    and then tweaked the equation a bit to change the shape.

    I teach at the School of Visual Arts in NYC.

  3. away4m
    Posted December 14, 2008 at 4:18 pm | Permalink

    why do you need calculate zpos again ?
    zpos= py*siny+ zpos*cosy ;

  4. Posted December 15, 2008 at 12:24 pm | Permalink

    It’s pretty complex, but there is a good explanation here

One Trackback

  1. [...] A 3D shape created with setPixel(). [...]

Post a Comment

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

*
*