0
我在舞台中央放置了一个大球“centerBall”。然后我在 中添加了一些较小的,给它们随机的大小和速度。这些将随基本运动代码一起移动并从墙壁反弹。在每个框架上,在每个移动的球和中心球之间进行基于距离的碰撞检查。如果碰撞,我已经根据两个球之间的角度和最小距离计算了一个偏置弹簧目标。 还有一个问题:一些较小的球绕过“中心球”的边界,然后反弹。你可以在附图中看到。为什么发生这种情况? 下面是代码:基于碰撞的弹跳
import flash.display.Sprite;
import flash.events.Event;
public class Bubbles extends Sprite
{
private var balls:Array;
private var numBalls:Number = 10;
private var centerBall:Ball;
private var bounce:Number = -1;
private var spring:Number = 0.2;
public function Bubbles()
{
init();
}
private function init():void
{
balls = new Array();
centerBall = new Ball(100, 0xcccccc);
addChild(centerBall);
centerBall.x = stage.stageWidth/2;
centerBall.y = stage.stageHeight/2;
for(var i:uint = 0; i < numBalls; i++)
{
var ball:Ball = new Ball(Math.random() * 40 + 5, 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, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
for(var i:uint = 0; i < numBalls; i++)
{
var ball:Ball = balls[i];
move(ball);
var dx:Number = ball.x - centerBall.x;
var dy:Number = ball.y - centerBall.y;
var dist:Number = Math.sqrt(dx * dx + dy * dy);
var minDist:Number = ball.radius + centerBall.radius;
if(dist < minDist)
{
var angle:Number = Math.atan2(dy, dx);
var targetX:Number = centerBall.x + Math.cos(angle) * minDist;
var targetY:Number = centerBall.y + Math.sin(angle) * minDist;
ball.vx += (targetX - ball.x) * spring;
ball.vy += (targetY - ball.y) * spring;
}
}
}
private function move(ball:Ball):void
{
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;
}
}
}
是的,你说得对。我做了一些研究 – LuciM
是的,你说得对。问题是我在当前帧中进行碰撞测试,而不是之前的测试。屏幕更新,我看到进入大球的小球。我已经做了一些研究,并提出了一个简单的公式:Verlet集成不计算对象的当前位置。相反,它是根据与当前帧和最后一帧的差异来计算对象的速度。关键是测试屏幕之间的碰撞检测更新位置。 – LuciM
很高兴帮助:) –