forked from: DRAG AND MOVE
Main
メインクラス.
/**
* Copyright kazy ( http://wonderfl.net/user/kazy )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/qZN6
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* Main
* メインクラス.
*/
public class Main extends Sprite {
private var ball:Ball;
private var vx:Number;
private var vy:Number;
private var bounce:Number = -0.7;
private var gravity:Number = .5;
private var oldX:Number;
private var oldY:Number;
/**
* コンストラクタ.
*/
public function Main() {
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(event:Event):void {
vy += gravity;
ball.x += vx;
ball.y += vy;
//ステージ端の位置を取得
var left:Number = 0;
var right:Number = stage.stageWidth;
var top:Number = 0;
var bottom:Number = stage.stageHeight;
//ステージの端に行ったら方向を変える
if (ball.x + ball.radius > right) {
ball.x = right - ball.radius;
vx *= bounce;
} else if (ball.x - ball.radius < left) {
ball.x = left + ball.radius;
vx *= bounce;
}
if (ball.y + ball.radius > bottom) {
ball.y = bottom - ball.radius;
vy *= bounce;
} else if (ball.y - ball.radius < top) {
ball.y = top + ball.radius;
vy *= bounce;
}
}
private function onMouseDown(event:MouseEvent):void {
//現状のボールの位置を記憶
oldX = ball.x;
oldY = ball.y;
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
ball.startDrag();
//onEnterFrame削除
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);
//onEnterFrame復帰
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;
}
}
}
/**
* Ball
* ボール生成クラス.
*/
class Ball extends flash.display.Sprite {
public var radius:Number;
private var color:uint;
public var vx:Number = 0;
public var vy:Number = 0;
/**
* コンストラクタ.
*/
public function Ball(radius:Number=40, color:uint=0x990033) {
this.radius = radius;
this.color = color;
init();
}
/**
* 初期化.
*/
public function init():void {
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
}