package { import flash.display.Sprite; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.ui.Keyboard; import net.hires.debug.Stats; [SWF(frameRate=30, width=465, height=465, backgroundColor=0xffffff)] public class Main extends Sprite { public static const NUM_HANDLES:int = 4; public static const SPRING:Number = 0.15; public static const FRICTION:Number = 0.8; private var handles:Vector.<Ball>; private var ball:Ball; private var stats:Stats; /** * コンストラクタ */ public function Main() { addEventListener(Event.ADDED_TO_STAGE, initialize); } /** * 初期化 */ private function initialize(evt:Event):void { removeEventListener(Event.ADDED_TO_STAGE, initialize); var i:int, b:Ball; handles = new Vector.<Ball>(NUM_HANDLES, true); for (i=0; i<NUM_HANDLES; i++) { b = new Ball(5, 0xa8a8a8); b.x = Math.random() * stage.stageWidth; b.y = Math.random() * stage.stageHeight; b.buttonMode = true; b.addEventListener(MouseEvent.MOUSE_DOWN, dragged); handles[i] = b; addChild(b); } ball = new Ball(20, 0xff3c3c); addChild(ball); // for debug. stats = new Stats(); stats.visible = false; addChild(stats); addEventListener(MouseEvent.MOUSE_UP, dropped); addEventListener(Event.ENTER_FRAME, step); stage.addEventListener(KeyboardEvent.KEY_DOWN, toggle); } /** * 毎フレームの処理 */ private function step(evt:Event):void { var i:int, b:Ball, dx:Number, dy:Number; for (i=0; i<NUM_HANDLES; i++) { b = handles[i] as Ball; dx = b.x - ball.x; dy = b.y - ball.y; ball.vx += dx * SPRING; ball.vy += dy * SPRING; } ball.vx *= FRICTION; ball.vy *= FRICTION; ball.x += ball.vx; ball.y += ball.vy; graphics.clear(); graphics.lineStyle(1, 0xa8a8a8); for (i=0; i<NUM_HANDLES; i++) { b = handles[i] as Ball; graphics.moveTo(ball.x, ball.y); graphics.lineTo(b.x, b.y); } } /** * ドラッグ時の処理 */ private function dragged(evt:MouseEvent):void { evt.target.startDrag(); } /** * ドロップ時の処理 */ private function dropped(evt:MouseEvent):void { stopDrag(); } /** * キータイプ時の処理 * ctrl + space で Stats の表示を切り替え */ private function toggle(evt:KeyboardEvent):void { if (evt.keyCode == Keyboard.SPACE && evt.ctrlKey == true) { stats.visible = !stats.visible; } } } } import flash.display.Sprite; class Ball extends Sprite { public var vx:Number; public var vy:Number; public function Ball(radius:Number=3, color:uint=0) { vx = 0; vy = 0; graphics.clear(); graphics.beginFill(color); graphics.drawCircle(0, 0, radius); graphics.endFill(); } } バネの復習とか