topical media & game development

talk show tell print

animation-ch15-RotateY.ax

animation-ch15-RotateY.ax [swf] [flash] flex


  package {
   import flash.display.Sprite;
   import flash.display.StageAlign;
   import flash.display.StageScaleMode;
   import flash.events.Event;
  
   public class @ax-animation-ch15-RotateY extends Sprite
   {
    private var balls:Array;
    private var numBalls:uint = 50;
    private var fl:Number = 250;
    private var vpX:Number = stage.stageWidth / 2;
    private var vpY:Number = stage.stageHeight / 2;
    
    public function @ax-animation-ch15-RotateY()
    {
     init();
    }
  

init(s)


    private function init():void
    {
     stage.align = StageAlign.TOP_LEFT;
     stage.scaleMode = StageScaleMode.NO_SCALE;
     
     balls = new Array();
     for(var i:uint = 0; i < numBalls; i++)
     {
      var ball:animation_ch15_Ball3D = new animation_ch15_Ball3D(15);
      balls.push(ball);
      ball.xpos = Math.random() * 200 - 100;
      ball.ypos = Math.random() * 200 - 100;
      ball.zpos = Math.random() * 200 - 100;
      addChild(ball);
     }
     addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }
   

frame(s)


    private function onEnterFrame(event:Event):void
    {
     var angleY:Number = (mouseX - vpX) * .001;
     for(var i:uint = 0; i < numBalls; i++)
     {
      var ball:animation_ch15_Ball3D = balls[i];
      rotateY(ball, angleY);
     }
     sortZ();
    }
  

rotate Y


    
    private function rotateY(ball:animation_ch15_Ball3D, angleY:Number):void
    {
     var cosY:Number = Math.cos(angleY);
     var sinY:Number = Math.sin(angleY);
     
     var x1:Number = ball.xpos * cosY - ball.zpos * sinY;
     var z1:Number = ball.zpos * cosY + ball.xpos * sinY;
     
     ball.xpos = x1;
     ball.zpos = z1;
     
     
     if(ball.zpos > -fl)
     {
      var scale:Number = fl / (fl + ball.zpos);
      ball.scaleX = ball.scaleY = scale;
      ball.x = vpX + ball.xpos * scale;
      ball.y = vpY + ball.ypos * scale;
      ball.visible = true;
     }
     else
     {
      ball.visible = false;
     }
    }
   

sort Z


    private function sortZ():void
    {
     balls.sortOn("zpos", Array.DESCENDING | Array.NUMERIC);
     for(var i:uint = 0; i < numBalls; i++)
     {
      var ball:animation_ch15_Ball3D = balls[i];
      setChildIndex(ball, i);
     }
    }
   }
  }
  


(C) Æliens 04/09/2009

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.