为什么我的球消失了
Why are my balls disappearing?
请原谅这个有趣的标题。我创建了一个小图形演示,其中有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);
}
您的错误最初来自以下行:
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);
相关文章:
- D3.js剪辑路径截断了我的图的边缘
- 清单文件中的update_url禁用了我的chrome扩展
- JQuery Mobile破坏了我的布局:如何禁用自动打字
- 闭包编译器--调试解决了我的错误
- RequireJS减慢了我的Web应用程序的负载
- 约曼发电机有棱角的咕哝发球:dist打断了我的应用程序
- 为什么require.js似乎在初始页面加载时加载了我的所有模块
- JQuery破坏了我的功能吗
- Django混合了我的模板
- Uglifier是不是弄坏了我的睡衣
- 不存在的XML节点破坏了我的脚本
- 仅限Chrome:ajax冻结了我的JavaScript执行
- 为什么d3忽略了我的颜色数组
- if语句禁用了我的jquery函数/按钮
- 是什么导致了我的scrollTo函数出现问题
- 为什么可以't我在html上启动了我的LibGDX项目
- 为什么 JQuery 附加颠倒了我的语句顺序
- AngularJS element.find更改了我的对象
- AdBlock阻止了我的一个页面
- 引导工具提示已经禁用了我的javascript部分