flash on 2009-6-26
/**
* Copyright dakkie ( http://wonderfl.net/user/dakkie )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/3NpX
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class ThrowBall extends Sprite {
private var ball:Ball;
private var vx:Number;
private var vy:Number;
private var bounce:Number = -0.5;
private var gravity:Number = .5;
private var oldX:Number;
private var oldY:Number;
public function ThrowBall() {
init();
}
private function init():void {
ball = new Ball();
ball.x = stage.stageWidth / 2;
ball.y = stage.stageHeight / 2;
vx = Math.random() * 10 - 5;
vy = -10;
addChild(ball);
ball.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e:Event):void {
vy += gravity;
ball.x += vx;
ball.y += vy;
if (ball.x + ball.radius > stage.stageWidth) {
ball.x = stage.stageWidth - ball.radius;
vx *= bounce;
}
else if (ball.x - ball.radius < 0) {
ball.x = ball.radius;
vx *= bounce;
}
if (ball.y + ball.radius > stage.stageHeight) {
ball.y = stage.stageHeight - ball.radius;
vy *= bounce;
}
else if (ball.y - ball.radius < 0) {
ball.y = ball.radius;
vy *= bounce;
}
}
private function onMouseDown(event:MouseEvent):void {
oldX = ball.x;
oldY = ball.y;
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
ball.startDrag();
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
addEventListener(Event.ENTER_FRAME, trackVelocity);
}
private function onMouseUp(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
ball.stopDrag();
removeEventListener(Event.ENTER_FRAME, trackVelocity);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function trackVelocity(event:Event):void {
vx = ball.x - oldX;
vy = ball.y - oldY;
oldX = ball.x;
oldY = ball.y;
}
}
}
import flash.display.Sprite;
class Ball extends Sprite {
public var vx:Number = 0;
public var vy:Number = 0;
public var radius:Number = 30;
public function Ball(){
init();
}
public function init():void {
graphics.beginFill(0x0000ff);
graphics.drawCircle(0,0,30);
graphics.endFill();
}
}