flash on 2009-6-22
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
[SWF(width=465,height=465,frameRate=30,background=0xf)]
public class ThrowBall extends Sprite
{
private static const CUSHION:Number=.5;
private static const GRAVITY:Number=.7;
private var myBall:Ball;
private var latestX:Number=0;
private var latestY:Number=0;
public function ThrowBall()
{
this.addEventListener(Event.ADDED_TO_STAGE,init);
}
private function init(e:Event):void
{
this.addEventListener(Event.ADDED_TO_STAGE,init);
myBall=new Ball();
myBall.x=stage.stageWidth/2;
myBall.y=stage.stageHeight/2;
this.addChild(myBall);
this.addEventListener(Event.ENTER_FRAME,loop);
myBall.addEventListener(MouseEvent.MOUSE_DOWN,ballMouseDown,false,0,true);
}
private function loop(e:Event):void
{
myBall.x+=myBall.vx;
myBall.y+=myBall.vy;
myBall.vx*=.96;
myBall.vy*=.96;
myBall.vy+=GRAVITY;
//四隅でのクッション
cushion();
}
private function ballMouseDown(e:Event):void
{
this.removeEventListener(Event.ENTER_FRAME,loop);
this.addEventListener(Event.ENTER_FRAME,track);
stage.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
myBall.startDrag(true);
latestX=myBall.x;
latestY=myBall.y;
}
private function onMouseUp(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP,onMouseUp);
this.removeEventListener(Event.ENTER_FRAME,track);
this.addEventListener(Event.ENTER_FRAME,loop);
myBall.stopDrag();
}
private function track(e:Event):void
{
myBall.vx=myBall.x-latestX;
myBall.vy=myBall.y-latestY;
latestX=myBall.x;
latestY=myBall.y;
}
private function cushion():void
{
if(myBall.x>stage.stageWidth){
myBall.x=stage.stageWidth;
myBall.vx*=-1*CUSHION;
}else if(myBall.x<0){
myBall.x=0;
myBall.vx*=-1*CUSHION;
}
if(myBall.y>stage.stageHeight){
myBall.y=stage.stageHeight;
myBall.vy*=-1*CUSHION;
}else if(myBall.y<0){
myBall.y=0;
myBall.vy*=-1*CUSHION;
}
}
}
}
import flash.display.Sprite;
class Ball extends Sprite{
public var vx:Number;
public var vy:Number;
public function Ball()
{
vx=10;
vy=10;
init();
}
private function init():void
{
graphics.beginFill(0xff0000,1);
graphics.drawCircle(0,0,30);
graphics.endFill();
}
}