为什么我的球消失?

请原谅这个有趣的标题。 我创build了一个200个球弹跳和碰撞的小图示,两个都在墙上和对方。 你可以看到我目前在这里: http : //www.exeneva.com/html5/multipleBallsBouncingAndColliding/

问题是,每当他们相互碰撞,他们消失。 我不知道为什么。 有人可以看一看,帮助我吗?

更新:显然球数组有球坐标的NaN。 下面是我推球到arrays的代码。 我不完全确定坐标是如何得到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); } 

最初你的错误来自这一行:

 var direction1 = Math.atan2(ball1.velocitY, ball1.velocityX); 

你有ball1.velocitY (这是undefined ),而不是ball1.velocityY 。 所以Math.atan2给你的是NaN ,而NaN价值是通过你所有的计算来传播的。

这不是你错误的根源,但是你可能想在这四行上改变一些东西:

 ball1.nextX = (ball1.nextX += ball1.velocityX); ball1.nextY = (ball1.nextY += ball1.velocityY); ball2.nextX = (ball2.nextX += ball2.velocityX); ball2.nextY = (ball2.nextY += ball2.velocityY); 

你不需要额外的分配,只需要使用+=操作符:

 ball1.nextX += ball1.velocityX; ball1.nextY += ball1.velocityY; ball2.nextX += ball2.velocityX; ball2.nextY += ball2.velocityY; 

collideBalls函数中有一个错误:

 var direction1 = Math.atan2(ball1.velocitY, ball1.velocityX); 

它应该是:

 var direction1 = Math.atan2(ball1.velocityY, ball1.velocityX);