自由落下を2つの方法で

by kyab
♥0 | Line 60 | Modified 2010-02-05 23:19:05 | MIT License
play

ActionScript3 source code

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

package {
    import flash.display.Sprite;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	[SWF(backgroundColor="0x0", frameRate="100")]
	public class Main extends Sprite 
	{
		private static const  GRAVITY : Number = 12.8*0.0001;	//重力加速度×調整のための係数
		private var _velocity : Number;	//現在の落下速度
		private var _elapsed_time : uint; //落下開始からの経過時間
		
		//落下物
		private var _point:Shape;
		private var _point2:Shape;

		private var _timer:Timer;
		
		public function Main():void 
		{
			
			_point = new Shape();
			_point2 = new Shape();
			new Array(_point, _point2).forEach(function(point:Shape, index:int, _:Array):void {
				with (point) {
					graphics.beginFill(0x00FF00);
					graphics.drawCircle(0, 0, 10);
					graphics.endFill();
					x = 100 * (index + 1);
					y = 10;
				}
				addChild(point);
			});
			
			_timer = new Timer(10);
			_timer.addEventListener(TimerEvent.TIMER, onTimer);
			_timer.addEventListener(TimerEvent.TIMER, onTimer2);
			
			_velocity = 0;
			_elapsed_time = 0;
			
			_timer.start();		
		}
		
		//積分
		private function onTimer(evt:TimerEvent = null):void {
			//今回の速度 = 前回の速度  + GRAVITY * 前回からの経過時間 
			_velocity +=  GRAVITY * _timer.delay;
			
			//今回動いた距離 = 今回の速度 * 前回からの経過時間
			var distance : Number = _velocity * _timer.delay;
			_point.y += distance;
			
			if (_point.y > stage.stageHeight) {
				reset();
			}
		}
		
		//方程式ベース。位置 =1/2 * GRAVITY * t^2
		// see http://www12.plala.or.jp/ksp/formula/physFormula/html/node4.html
		private function onTimer2(evt:TimerEvent = null):void {
			
			//現在の時間
			_elapsed_time += _timer.delay;
			
			//位置 =1/2 * GRAVITY * 時間
			var position : Number = 1 / 2 * GRAVITY * _elapsed_time * _elapsed_time;
			_point2.y = position + 10;
			
			if (_point2.y > stage.stageHeight) {
				reset();
			}
		}
		
		//位置や早さ、経過時間をリセット
		private function reset():void {
			_velocity = 0;
			_elapsed_time = 0;
			_point.y = _point2.y = 10;
		}
		
	}
}