There is a small problem with the physics you are doing in the first code block. If you are trying to model gravitational pull, you will want to compute your acceleration using Newton's Law of Gravitation. What you have currently, is Hooke's Law; a spring force, with linear drag. To immediately answer your question about how to move the center of attraction away from the point (0,0), you can simply change what you have to include an offset. Namely,
return1.Xaccel = -k * (state.pos.getX() - xOffset) - b* state.vel.getX();
return1.Yaccel = -k * (state.pos.getY() - yOffset) - b* state.vel.getY();
where xOffset
and yOffset
define the (x,y) position of your desired center of attraction. This would allow you to move your force source, but this still has not addressed the problem that your force is elastic, not gravitational (inverse-square law). To do this, you will want something that looks like the following
float dx = state.pos.getX() - xOffset; // again xOffset is the source location
float dy = state.pos.getY() - yOffset;
float distSqrd = dx*dx + dy*dy;
float dist = sqrt( distSqrd );
return1.Xaccel = -G * mass * dx / (distSqrd * dist);
return1.Yaccel = -G * mass * dy / (distSqrd * dist);
Notice that, in order to take the direction into account, I have multiplied the F = G*m1*m2/dist^2
by dx/dist
and dy/dist
. This is equivalent to cos(angle)
and sin(angle)
where angle
is a quantity best left uncomputed (that would specify the direction of the force). mass
would be the mass of the object that is attracting your particles(?), and the particle mass is left off since we are only computing acceleration. If you want to add the linear drag back into the acceleration, you can easily do that too, which will make orbits far more stable.
Do note that this code can be considerably cleaned up by using vectors. Let me know if any clarification is needed.