Escape Theory Programming, Flash and Gaming For Life…

3Jun/101

Flexperiment 1: Physics of a Bouncing, throwable ball.

Here is a simple bit of code that demonstrates simulated physics of a ball being thrown (written with my colleague Anthony http://www.creatistblog.com/):

The keystone of this experiment is the ENTER FRAME event function that tracks the motion of the ball, applying horizontal 'drag' and vertical 'gravity' as well as spelling out the boundaries of the ball's movement area. A simple hack forces the ball to stop in its tracks when it is at a certain speed and distance from the 'ground' or bottom of the screen. Understanding the physics of something like a bouncing ball helps me build on top of it with more features (such as a true collision detection system, or adding wind).

package {  import flash.display.Graphics;  import flash.display.Sprite;  import flash.events.*;  [ SWF( frameRate="60", width="420", height="420", backgroundColor="0x000000" ) ]  public class BouncingBall extends Sprite {  private var maxSpeed:Number = 100;  private var radius:Number = 25;  private var vx:Number;  private var vy:Number;  private var ball:Sprite;  private var previousMouseX:Number=0;  private var previousMouseY:Number=0;  private var currentMouseX:Number;  private var currentMouseY:Number;  private var throwX:Number;  private var throwY:Number;  public function BouncingBall() {  ball = new Sprite();  ball.buttonMode=true;  ball.addEventListener(MouseEvent.MOUSE_DOWN, ballDownHandler);  ball.addEventListener(MouseEvent.MOUSE_UP, ballUpHandler);  addChild( ball );  ball.x = Math.random() * ( stage.stageWidth - radius );  ball.y = Math.random() * ( stage.stageHeight - radius );  vx = Math.random() * maxSpeed + 0.5;  vy = Math.random() * maxSpeed + 0.5;  var g:Graphics = ball.graphics;  g.beginFill( 0xFF0000 );  g.drawCircle( 0, 0, radius );  g.endFill();  addEventListener( Event.ENTER_FRAME, onClipEnterFrame, false, 0, true );  }  private function onClipEnterFrame( p_event:Event ):void {  currentMouseX = this.mouseX;  currentMouseY = this.mouseY;  ball.x += vx;  ball.y += vy;  if ( vy != 0 ) vy += 0.5;  if ( vx != 0 ) vx += (0-vx)*0.015;  if ( ( ball.x <= radius && vx < 0 ) || ( ball.x >= stage.stageWidth - radius && vx > 0 ) ) {  vx = -vx * 0.6;  }  if ( ( ball.y <= radius && vy < 0 ) || ( ball.y >= stage.stageHeight - radius && vy > 0 ) ) {  vy = -vy * 0.6;      }  if ( Math.abs( vx ) < 0.01 ) vx = 0;  if ( Math.abs( vy ) < 0.1 && ball.y>=stage.stageHeight-radius-2){  vy = 0;  ball.y=stage.stageHeight-radius;  }  throwX = currentMouseX - previousMouseX;  throwY = currentMouseY - previousMouseY;  previousMouseX = currentMouseX;  previousMouseY = currentMouseY;  }  public function ballDownHandler(e:MouseEvent):void{  ball.startDrag(true);  vy = vx = 0;  }  public function ballUpHandler(e:MouseEvent):void{  ball.stopDrag();  vx = throwX;  vy = throwY - 0.6;  }  } }
Comments (1) Trackbacks (0)

Leave a comment

(required)

No trackbacks yet.