Velocity and Acceleration

Accomplishing velocity and acceleration in 3D is surprisingly easy. For 2D, you had vx and vy variables to represent velocity on two axes. You just need to add a vz for the third dimension. Similarly, if you have something like ax and ay for acceleration, you just add an az variable.

You can alter the last example to make it work sort of like the Asteroids spaceship, but in 3D. Lets make it all keyboard-controlled now. Cursor keys can provide thrust on the x and y axes, and well grab a couple other keys, say SHIFT and CTRL , for z thrust.

Heres the code ( ch15_03.fla ):

 var x:Number = 0; var y:Number = 0; var z:Number = 0;  var vx:Number = 0;   var vy:Number = 0;   var vz:Number = 0;   var friction:Number = .98;  var fl:Number = 250; var vpX:Number = Stage.width / 2; var vpY:Number = Stage.height / 2; function onEnterFrame():Void {  if(Key.isDown(Key.UP))   {   vy -= 1;   }   else if(Key.isDown(Key.DOWN))   {   vy += 1;   }   if(Key.isDown(Key.LEFT))   {   vx -= 1;   }   else if(Key.isDown(Key.RIGHT))   {   vx += 1;   }   if(Key.isDown(Key.SHIFT))   {   vz += 1;   }   else if(Key.isDown(Key.CONTROL))   {   vz -= 1;   }   x += vx;   y += vy;   z += vz;   vx *= friction;   vy *= friction;   vz *= friction;  if(z <= -fl)       {             ball._visible = false;       }       else       {             ball._visible = true;             var scale:Number = fl / (fl + z);             ball._xscale = ball._yscale = scale * 100;             ball._x = vpX + x * scale;             ball._y = vpY + y * scale;       } } 

All youve done here is add variables for velocity on each axis and some friction. When one of the six keys is pressed, it adds or subtracts from the appropriate velocity (remember that acceleration changes velocity). Then it adds the velocity to the position on each axis and computes friction.

Now you have a 3D object moving with acceleration, velocity, and friction. Wow, three birds with one stone. I told you it was easy.



Foundation ActionScript. Animation. Making Things Move
Foundation Actionscript 3.0 Animation: Making Things Move!
ISBN: 1590597915
EAN: 2147483647
Year: 2005
Pages: 137
Authors: Keith Peters

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net