我正在编写一个“物理模拟”(可以这么说),使用键盘箭头可以将力施加到球体上。在这最新的迭代中,我添加了拖动,就像球体在空中一样。然后,对于某些值,拖动计算开始爆炸!数字变得太大,然后是Infinity,就在NaN之后(无限/无限分裂的原因)。
你可以在这里看到它:http://gool.jit.su/the-drag。打开控制台,开始向左或向右移动。几秒钟后它就会破裂。您可以在控制台中看到记录的拖动值,直到它变为NaN。 (我们有很大的力量和非常小的质量)
我真的想了解发生了什么以及发生了什么,但也许已经有类似问题的信息我无法找到或者某种最佳做法可以控制数量...也许选择一个值作为我的MAX并每次测试它......
非常欢迎任何想法,帮助和建议。我想我即将学习一些重要的东西,但仍需要朝着正确的方向努力。 :)
更新2 :@ Beta测试(sorta)
在@ Beta的评论之后,我做了这个测试,实际上他的计算似乎显示了我的模拟分解的地方。 (当测试返回true时,控制台在x轴上记录速度,否则为false)
更新1 :有些代码
大多数“物理学”发生在这里:
update: function update(k, dt) {
var up = k.UP,
right = k.RIGHT,
down = k.DOWN,
left = k.LEFT;
up = up && -this.output;
right = right && this.output;
down = down && this.output;
left = left && -this.output;
this.force.x = left + right;
this.force.y = up + down;
this.calculate_drag(this.velocity);
if (!isNaN(this.drag.x)) {
console.log(this.drag);
}
// this.net_force.x = this.force.x;
// this.net_force.y = this.force.y;
this.net_force.x = this.force.x + this.drag.x;
this.net_force.y = this.force.y + this.drag.y;
this.acceleration.x = this.net_force.x / this.mass;
this.acceleration.y = this.net_force.y / this.mass;
this.velocity.x += this.acceleration.x / (1000 / dt);
this.velocity.y += this.acceleration.y / (1000 / dt);
this.momentum.x = this.mass * this.velocity.x;
this.momentum.y = this.mass * this.velocity.y;
this.position.x += (this.velocity.x * global.METRE) / (1000 / dt);
this.position.y += (this.velocity.y * global.METRE) / (1000 / dt);
this.energy += (abs(this.net_force.x) + abs(this.net_force.y)) / (1000 / dt);
}
在这里:
calculate_drag: function calculate_drag() {
var c = 0.47,
a = PI * this.radius * this.radius,
rho = 1.22,
direction = function direction(velocity) {
if (velocity === 0) {
return 1;
}
return velocity / abs(velocity);
};
this.drag.x = -0.5 * c * a * rho * this.velocity.x * this.velocity.x * direction(this.velocity.x);
this.drag.y = -0.5 * c * a * rho * this.velocity.y * this.velocity.y * direction(this.velocity.y);
}
gee.js中的两种gPrototype方法。
答案 0 :(得分:0)
你有一个增加变量值的循环。价值观会快速增长。 NaN可能是一些浮动溢出的结果。
net_force += drag;
drag = velocity * velocity;
velocity += net_force;
所以你的“物理”可能不正确。