为什么我的球消失了?[关闭]


202

原谅有趣的标题。我创建了一个小图形演示,演示了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);
}

119
即使只有本年度最佳问题标题,这也能赢得我的投票!!
Alex

Answers:


97

您的错误最初来自此行:

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

ball1.velocitY(这是undefined)代替ball1.velocityYMath.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;

20

collideBalls函数中存在错误:

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

它应该是:

var direction1 = Math.atan2(ball1.velocityY, ball1.velocityX);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.