2つの物体の衝突

by _wonder forked from base (diff: 46)
♥0 | Line 56 | Modified 2010-06-02 12:21:46 | MIT License
play

ActionScript3 source code

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

// forked from _wonder's base
package {
    import flash.display.Sprite;
    import flash.events.Event;
    
    public class Billiard extends Sprite {
    		private var ball0:Ball;
    		private var ball1:Ball;
    		
    		public function Billiard() {
            init();
        }
        
        private function init():void {
        		ball0 = new Ball(40);
        		ball0.mass = 2;
        		ball0.x = 50;
        		ball0.y = stage.stageHeight / 2;
        		ball0.vx = 1;
        		addChild( ball0 );
        		
        		ball1 = new Ball(25);
        		ball1.mass = 1;
        		ball1.x = 300;
        		ball1.y = stage.stageHeight / 2;
        		ball1.vx = -1;
        		addChild( ball1 );
        		
        		addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }
        
        private function onEnterFrame(e:Event):void {
        		ball0.x += ball0.vx;
        		ball1.x += ball1.vx;
        		
        		var dist:Number = ball0.x - ball1.x;
        		
        		if( Math.abs( dist ) < ball0.radius + ball1.radius ){
        			var vxTotal:Number = ball0.vx - ball1.vx;
        			ball0.vx = ( (ball0.mass - ball1.mass)*ball0.vx + 2*ball1.mass * ball1.vx ) / (ball0.mass + ball1.mass);
        			ball1.vx = vxTotal + ball0.vx;
        			
        			ball0.x += ball0.vx;
        			ball1.y += ball1.vx;
        		}
        }
    }
}

import flash.display.Sprite;

class Ball extends Sprite {
	public var radius:Number;
	public var color:uint;
	public var vx:Number = 0;
	public var vy:Number = 0;
	public var mass:Number = 1;
	
	public function Ball(radius:Number=40, color:uint=0Xff0000){
		this.radius = radius;
		this.color = color;
		init();
	}
	
	public function init():void {
		graphics.beginFill(color);
		graphics.drawCircle(0, 0, radius);
		graphics.endFill();
	}
}