I don’t know if this question get her place in physics.stackoverflow forum. I prefer post here, with code etc.
So, I want simulate 2D movements (no rotation) of an asteroid in space affected by a planet’s gravity, the problem is how integrate that ?
Any better integration for performance ?
Here is the code in C:
struct vec2
{
float x;
float y;
};
struct body
{
double mass; //kg
struct vec2 prev_pos; //for semi-implicit euler method
struct vec2 pos; //position
struct vec2 v; //velocity
};
void move_asteroid(float dt) {
//semi-implicit euler integration #1 -moving the object
asteroid.pos.x += asteroid.v.x * dt;
asteroid.pos.y += asteroid.v.y * dt;
//START
float x = planet.pos.x - asteroid.pos.x;
float y = planet.pos.y - asteroid.pos.y;
float d = x * x + y * y; //distance^2 between asteroid and center of planet
//acceleration
float ah = G * ((planet.mass * asteroid.mass) / d); //gravity
//get components of gravity
float rad = atan2(y, x);
float ax = ah * cos(rad);
float ay = ah * sin(rad);
//semi-implicit euler integration #2 -update velocity
asteroid.v.x += ax * dt;
asteroid.v.y += ay * dt;
}
this is for ‘fun’ and sadly my knowledge is quite not good, I try to find with my vocabulary (not native english), if you have directions, ideas for better implementation (like study RK4 for correctness etc), it’s welcome