美好的一天,我正在尝试用 javascript 创建一个简单的 2D 太阳系模型,但是在理解如何计算下一帧行星的位置以及其他一些我将详细介绍的部分时遇到了一些麻烦随着很快。
看完这个非常好的视频和他的一大堆其他视频后,我制作了一个快速的 MS 绘画图像来尝试简化我的情况。在第二个场景中,您可以看到新位置是使用速度、引力和这两个“方向”之间的角度来计算的?
我无法理解如何解决这一切。
Below is a JS fiddle of my code. You'll notice I'm trying my best to use real NASA given data to keep it accurate.
You'll want to look specifically at lines 138 which is where all the calculations for its next move are made.
https://jsfiddle.net/c8eru7mk/9/
attraction: function(p2) {
// Distance to other body
var dx = p2.position.x - this.position.x;
var dy = p2.position.y - this.position.y;
var d = Math.sqrt(dx ** 2 + dy ** 2); // Possibly correct
// Force of attracrtion
this.f = G * (this.mass * p2.mass) / (d ** 2); // Possibly Correct
// Direction of force, If you read it hard enough you should be able to hear my screams of pain
// Not sure if this is correct, most likely not.
var theta = Math.atan2(dy, dx);
var fx = Math.cos(theta) * this.f;
var fy = Math.sin(theta) * this.f;
this.velocity.x += fx / this.mass;
this.velocity.y += fy / this.mass;
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
}
The problems I'm currently facing are
This is also my first time actually coding anything more complex than a button in javascript too, so feedback on code layout and whatnot is welcome!
Many thanks
Using NASA values is not a problem when using separate coordinates for drawing. Using an appropriate linear transfomration from real coordinates to screen coordinatees for displaying does not influence the physical values and computations.
For simulating the motion of a planet with iterative updates one can assume that the gravitational force and the velocity are constant for a small portion of time dt
. This factor dt
is missing in your conversions from accelration to velocity and from velocity to distance. Choosing an appropriate value for dt
may need some experiments. If the value is too big the approximation will be too far off from reality. If the value is too small you may not see any movement or rounding errors may influence the result.
For the beginning let us assume that the sun is always at (0,0). Also for a start let us ignore the forces between the planets. Then here are the necessary formulas for a first not too bad approximation:
(x,y)
太阳引力作用下的标量加速度(质量为M
):a = G*M/(d*d)
其中d=sqrt(x*x+y*y)
。请注意,这与行星的质量无关。ax = -a*x/d
,ay = -a*y/d
(向量(-x,-y)
指向太阳,必须带上长度a
)(vx,vy)
:vx += ax*dt
,vy += ay*dt
x += vx*dt
,y += vy*dt
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句