ChatGPT解决这个技术问题 Extra ChatGPT

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

关闭。这个问题是不可重现的,或者是由拼写错误引起的。它目前不接受答案。此问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能帮助未来的读者。 8年前关闭。改进这个问题

原谅这个有趣的标题。我创建了一个 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);
}
这得到了我的投票,即使只是为了年度最佳问题标题!

P
Paul

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

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;

P
Paul

collideBalls 函数中存在错误:

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

它应该是:

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