抱歉取个有趣的标题。我制作了一个小的图形演示,有200个球在墙壁和彼此之间弹跳和碰撞。您可以在这里查看我目前的内容:http://www.exeneva.com/html5/multipleBallsBouncingAndColliding/
问题是每当它们互相碰撞时,它们就会消失。 我不确定原因。 能否有人看一下并帮助我解决?
更新:显然,球数组中有坐标为NaN的球。以下是将球推入数组的代码。 我不完全确定坐标如何成为NaN。
// Variables
var numBalls = 200; // number of balls
var maxSize = 15;
var minSize = 5;
var maxSpeed = maxSize + 5;
var balls = new Array();
var tempBall;
var tempX;
var tempY;
var tempSpeed;
var tempAngle;
var tempRadius;
var tempRadians;
var tempVelocityX;
var tempVelocityY;
// Find spots to place each ball so none start on top of each other
for (var i = 0; i < numBalls; i += 1) {
tempRadius = 5;
var placeOK = false;
while (!placeOK) {
tempX = tempRadius * 3 + (Math.floor(Math.random() * theCanvas.width) - tempRadius * 3);
tempY = tempRadius * 3 + (Math.floor(Math.random() * theCanvas.height) - tempRadius * 3);
tempSpeed = 4;
tempAngle = Math.floor(Math.random() * 360);
tempRadians = tempAngle * Math.PI/180;
tempVelocityX = Math.cos(tempRadians) * tempSpeed;
tempVelocityY = Math.sin(tempRadians) * tempSpeed;
tempBall = {
x: tempX,
y: tempY,
nextX: tempX,
nextY: tempY,
radius: tempRadius,
speed: tempSpeed,
angle: tempAngle,
velocityX: tempVelocityX,
velocityY: tempVelocityY,
mass: tempRadius
};
placeOK = canStartHere(tempBall);
}
balls.push(tempBall);
}