欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多物体碰撞检测

程序员文章站 2022-03-13 15:26:47
...
文档类
package {
import flash.display.Sprite;
import flash.events.Event;

/**
* ...多物体碰撞检测
* @author zkl
* 来自:Action Script3.0 Animation
*/
public class Bubbles2 extends Sprite {
private var balls:Array;
private var centerBall:Ball;
private var numBalls:Number = 10;
private var bounce:Number = -1;
private var spring:Number = 0.2;
private var gravity:Number = 0.1;

public function Bubbles2():void {
init();
}

private function init():void {
balls = new Array;

for (var i:uint = 0; i < numBalls; i++){
var ball:Ball = new Ball(Math.random() * 40 + 5, Math.random() * 40 + 5);
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, EnterFrame);
}

private function EnterFrame(e:Event):void {
//A球碰B球
for (var i:uint = 0; i < balls.length - 1; i++){
var ballA:Ball = balls[i];
for (var j:uint = i + 1; j < balls.length; j++){
var ballB:Ball = balls[j];
var dx:Number = ballB.x - ballA.x;
var dy:Number = ballB.y - ballA.y;
var dist:Number = Math.sqrt(dy * dy + dx * dx);
var minDist:Number = ballB.radius + ballA.radius;
if (dist < minDist){
var angle:Number = Math.atan2(dy, dx);
var tx:Number = ballA.x + Math.cos(angle) * minDist;
var ty:Number = ballA.y + Math.sin(angle) * minDist;
//计算加速度
var ax:Number = (tx - ballB.x) * spring;
var ay:Number = (ty - ballB.y) * spring;
//AB球加速度相反
ballA.vx -= ax;
ballA.vy -= ay;
ballB.vx += ax;
ballB.vy += ay;
}
}
}
for (i = 0; i < numBalls; 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.radius > stage.stageWidth){
ball.x = stage.stageWidth - ball.radius;
ball.vx *= bounce;
} else if (ball.x - ball.radius < 0){
ball.x = ball.radius;
ball.vx *= bounce;
}
if (ball.y + ball.radius > stage.stageHeight){
ball.y = stage.stageHeight - ball.radius;
ball.vy *= bounce;
} else if (ball.y - ball.radius < 0){
ball.y = ball.radius;
ball.vy *= bounce;
}
}

}

}
相关标签: Spring Flash J#