# gravity simulation implementation

this.attract = function () {
for (let i = 0; i < numofplanets; i) {
var r = Math.sqrt(Math.pow(blackhole.x - planet[i].x, 2) + Math.pow(blackhole.y - planet[i].y, 2));
planet[i].acclx = (blackhole.mass(blackhole.x - planet[i].x)) / Math.pow(r, 3);
planet[i].accly = (blackhole.mass - (blackhole.y - planet[i].y)) / Math.pow(r, 3);
// planet[i].acclx=(blackhole.x-planet[i].x)/60000; without force implementation in which planets get sucked inside the blackhole
// planet[i].accly=(blackhole.y-planet[i].y)/60000; without force implementation in which planets get sucked inside the blackhole)
planet[i].speedy += planet[i].accly;
planet[i].x += planet[i].speedx;
planet[i].y += planet[i].speedy;
}
}


i am trying to create gravity simulation model for a game in JavaScript.i need planets to move around a black hole in elliptical orbits. first i calculate acceleration and then add it to velocity and according to that i calculate the next position of planet. i first tried with just calculating distance vector between planets and black hole but in that scenario planets directly gets sucked inside the black hole and i need them to move in elliptical orbits. i tried calculating acceleration due to gravity but i think formula is wrong so can you correct it or provide some other implementation.

• Would be much readable if you implemented it using some Vector class. Planets get sucked into hole? Have you tried giving planet Velocity vector that will be perpendicular to the black hole gravitational force vector and has at least the same magnitude? Edit: Also, I imagine, it would be much cooler if black hole was included in planet[] array. So it acted no different than any other celestial object, just with a bigger mass. – Nick May 27 at 17:38
• Nick, Bram and ScienceSnake are right, these kind of simulations must not start with stopped planets as such thing doesn't happen in real universe. @Nick, I guess he wants the planets to interact with the black hole and not with other planets, that's why he didn't add it to the planets array. – Hatoru Hansou May 27 at 23:33
• @HatoruHansou Thats exactly what i've said... About the array, i understand why he did this, just gave a suggestion – Nick May 28 at 10:05

@Bramm has the right answer. To be more specific, if you want a circular orbit, the planet starts at distance $$\r\$$ from the black hole and the acceleration is $$\a\$$ you want to give the planet an initial velocity of $$v = \sqrt{r a}$$ perpendicular to $$\r\$$. If you change the speed a little they will enter an elliptical orbit. If you change it too much they'll either get sucked in or fly out in a hyperbolic path.