We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I tried to make a gravity simulator based on one of Shiffman's recent videos. You can try it here: https://jsfiddle.net/Tsskyx/t7qztum8/
First, click on the window, and then you select the type of a particle you want to spawn. Press left arrow to spawn a massless particle (it won't affect other particles by its presence), right to spawn a one with mass, down to spawn a stationary mass particle (it won't move) and up to spawn a stationary particle with repulsion effect. You can assign each particle a velocity vector by dragging before releasing the mouse (this won't have an effect on the stationary types), and you can set the mass of the particles by scrolling before releasing the mouse (this won't have an effect on the massless particles).
The problem here is that I don't like the way it behaves. The orbits are really unstable, and if you just let a particle fall towards a mass point (that is, without giving it a velocity vector first), it will be launched away from it at insane speeds. The calculation for the particle's velocity happens on lines 7 and 8:
var force = new p5.Vector.sub(attractor.pos, this.pos);
this creates a "force" vector, that shows the direction of attraction for this particle.
this.acc.add(force.setMag(50*attractor.mass/force.magSq()));
this edits the magnitude of the said vector, based on the classical F=G*m1*m2/d^2
equation.
I think I know why this is happening. If you turn the said equation into a graph, you'll see that F reaches insane values when d is near 0. I tried to get around this, but it never works, there's always a spike in acceleration when the particle winds too close to the attractor (for example, I tried equations like y=1/(abs(x)+1)^2
, which look promising when graphed, but don't really work; at least I can't seem to get them to work). But what bugs me the most is how unstable the orbits are. Sometimes the particle spazms around the attractor, sometimes it gets launched away.
I'd like the program to work like this game here: http://dan-ball.jp/en/javagame/ee/ Click on "PEN-rand" twice, and then click anywhere on the screen. You'll see the particle moving around the white point in regular intervals, like a pendulum. I'd like my program to do the same, but I don't know which equations to use. Essentially, I don't know how to program a 2D pendulum :(
EDIT: I tweaked the equation on line 8 a bit.