【发布时间】:2020-09-14 11:53:27
【问题描述】:
我正在开发一个物理沙盒。每个物体都有自己的属性,如质量、速度和加速度。默认情况下,所有物体都会落到地上,但其中一些物体具有可以吸引其他物体的引力场。我试图计算身体的移动向量并将它们相加,但它不起作用。如何正确实施这个景点?
class Body {
// Physical properties
position = { x: 0, y: 0 }
velocity = { x: 0, y: 0 }
acceleration = { x: 0, y: 0 }
mass = 1.0;
gravity = 0.0;
// ... class constructord and etc.
move = () => {
if(this.checkCollision == true) return;
this.setVelocityVector();
this.position.y += this.velocity.y;
this.position.x += this.velocity.x;
}
setVelocityVector = () => {
// By default body falls down
this.acceleration.y = this.mass * GRAVITY_ACCELERATION;
// Check gravity body's attraction
activeParticles.forEach(body => {
if(body.gravity > 0) {
// Calculate gravity power with Newton's formula:
// F = G * m1 * m2 / r^2
var rr = (this.position.x - body.position.x) * (this.position.x - body.position.x)
+ (this.position.y - body.position.y) * (this.position.y - body.position.y);
var a = body.gravity * this.mass * body.mass / rr;
this.acceleration.x += a;
this.acceleration.y += a;
}
});
this.velocity.y += this.acceleration.y;
this.velocity.x += this.acceleration.x;
}
}
【问题讨论】:
-
一方面,您不能在迭代每个物体时修改它们的坐标或速度;您需要计算新值,然后在时间步结束时将它们分配回主体。
-
你在哪里叫秋天?
-
@EliasSoares 从渲染游戏的外部函数调用
标签: javascript math simulation game-physics gravity