GRAVITY BALL

by kazy
♥0 | Line 68 | Modified 2009-06-01 22:15:04 | MIT License
play

ActionScript3 source code

/**
 * Copyright kazy ( http://wonderfl.net/user/kazy )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/3a4C
 */

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
	public class Main extends Sprite
	{
		private var ball:Sprite;
		private var vx:Number = 0;
		private var ax:Number = 0
		private var outputText:TextField = new TextField();
		
		public function Main()
		{
			init();
		}
		
		private function init():void
		{
			outputText.autoSize = TextFieldAutoSize.LEFT;
			outputText.text = "Push ← → key";
			outputText.x = 10
			outputText.y = 10
			addChild(outputText);
			//
			ball = makeBall();
			addChild(ball);
			ball.x = stage.stageWidth / 2;
			ball.y = stage.stageHeight / 2;
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		}
		
		private function onKeyDown(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.LEFT)
			{
				ax = -0.2;
			}
			else if(event.keyCode == Keyboard.RIGHT)
			{
				ax = 0.2;
			}
		}
		
		private function onKeyUp(event:KeyboardEvent):void
		{
			ax = 0;
		}
		
		private function onEnterFrame(event:Event):void
		{
			vx += ax;
			
			if (ball.x > stage.stageWidth + ball.width/2) {
				ball.x = - ball.width/2;
			}else if (ball.x < - ball.width/2) {
				ball.x = stage.stageWidth + ball.width/2;
			}else {
				ball.x += vx;
			}
			
		}
		
		private function makeBall():Sprite {
			var newBall:Sprite = new Sprite;
			newBall.graphics.beginFill(0x990033);
			newBall.graphics.drawCircle(0, 0, 20);
			newBall.graphics.endFill();
			return newBall;
		}
		
	}
}