笔记:基于距离的多物体碰撞检测

 

基本思路:两个圆的距离如果小于两圆半径只和就可以判定这两个圆发生碰撞了

var dx:Number = ball2.x - ball1.x;

var dy:Number = ball2.y - ball1.y;

var dist:Number = Math.sqrt(dx * dx + dy * dy);

if (dist < ball1.radius + ball2.radius) {

trace("hit");

}

  

package  {
	import flash.display.Sprite;
	public class Ball extends Sprite{
		public var vx:Number;
		public var vy:Number;
		public var r:Number;
		public function Ball(r:int=20,c:uint=0xff0000) {
			this.r=r;
			this.graphics.beginFill(c);
			this.graphics.drawCircle(0,0,r);
			this.graphics.endFill();
		}
	}
}

 

package 
{
	import flash.display.MovieClip;
	import flash.events.Event;

	public class Test extends MovieClip
	{
		private var balls:Array;
		private var bounce:Number = -0.5;
		private var spring:Number = 0.05;
		private var gravity:Number = 0.1;

		public function Test()
		{
			init();
		}
		private function init():void
		{
			balls = [];
			for (var i:int=0; i<50; i++)
			{
				var ball:Ball = new Ball(Math.random() * 30 + 20,Math.random() * 0xffffff);
				ball.x = Math.random() * stage.stageWidth;
				ball.y = Math.random() * stage.stageHeight;
				ball.vx = Math.random() * 6 - 3;
				ball.vy = Math.random() * 6 - 3;
				addChild(ball);
				balls.push(ball);
			}
			addEventListener(Event.ENTER_FRAME,onLoop);
		}
		private function onLoop(e:Event):void
		{
			for (var i:uint = 0; i < balls.length - 1; i++)
			{
				var ball0:Ball = balls[i];
				for (var j:uint = i + 1; j < balls.length; j++)
				{
					var ball1:Ball = balls[j];
					var dx:Number = ball1.x - ball0.x;
					var dy:Number = ball1.y - ball0.y;
					var dis:Number = Math.sqrt(dx * dx + dy * dy);
					var r:Number = ball0.r + ball1.r;
					if (r > dis)
					{
						var angle:Number = Math.atan2(dy,dx);
						var tx:Number = ball0.x + Math.cos(angle) * r;
						var ty:Number = ball0.y + Math.sin(angle) * r;
						var ax:Number=(tx-ball1.x)*spring;
						var ay:Number=(ty-ball1.y)*spring;
						ball0.vx -=  ax;
						ball0.vy -=  ay;
						ball1.vx +=  ax;
						ball1.vy +=  ay;
					}
				}
			}
			for (i = 0; i < balls.length; i++)
			{
				var ball:Ball = balls[i];
				move(ball);
			}
		}
		private function move(ball:Ball):void
		{
			ball.vy +=  gravity;
			ball.x +=  ball.vx;
			ball.y +=  ball.vy;
			if (ball.x + ball.r > stage.stageWidth)
			{
				ball.x = stage.stageWidth - ball.r;
				ball.vx *=  bounce;
			}
			else if (ball.x - ball.r < 0)
			{
				ball.x = ball.r;
				ball.vx *=  bounce;
			}
			if (ball.y + ball.r > stage.stageHeight)
			{
				ball.y = stage.stageHeight - ball.r;
				ball.vy *=  bounce;
			}
			else if (ball.y - ball.r < 0)
			{
				ball.y = ball.r;
				ball.vy *=  bounce;
			}
		}
	}
}

posted @ 2010-09-02 22:58  rock506  阅读(267)  评论(0编辑  收藏  举报