为什么我的文件丢失了?

204

抱歉取个有趣的标题。我制作了一个小的图形演示,有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);
}

122
即使只是因为这是今年最佳问题标题,我也会支持这个观点! - Alex
2个回答

97

你的错误最初来自于这行代码:

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;

21

这个collideBalls函数有一个错误:

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

它应该是这样的:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接