203

おかしなタイトルはご容赦を。200 個のボールが跳ねたり、壁にぶつかったり、お互いに衝突したりする小さなグラフィック デモを作成しました。私が現在持っているものを見ることができます: http://www.exeneva.com/html5/multipleBallsBounceAndColliding/

問題は、それらが互いに衝突するたびに消えてしまうことです。理由はわかりません。誰かが見て、私を助けることができますか?

更新:明らかに、ボール配列には 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);
}
4

2 に答える 2

96

エラーは最初は次の行から発生します。

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

の代わりにball1.velocitY(です)があります。だからあなたに与えている、そしてその価値はあなたのすべての計算を通して伝播している。undefinedball1.velocityYMath.atan2NaNNaN

これはエラーの原因ではありませんが、次の4行で変更したいことがあります。

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;
于 2012-06-16T18:45:02.100 に答える
20

関数にエラーがありcollideBallsます:

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

そのはず:

var direction1 = Math.atan2(ball1.velocityY, ball1.velocityX);
于 2012-06-16T18:46:46.147 に答える