|
Hello, this may not be exactly what you are looking for, but you can try this:
// Position of Planet b2Vec2 planetPos = planetLocation; // Position of Body b2Vec2 bodyPos = body->GetWorldCenter();
/***** To get the vector from the body to the planet, you subtract the planet position from the body position. For example, if the body's position is at the screen center, (160, 240), and the planet is at the upper right (300, 450), then subtracting the body position from the planet's position results in (300 - 160, 450 - 240) = (140, 210). ******/ b2Vec2 bodyToPlanetDirection = planetPos - bodyPos;
// Get the distance and store it, you'll see why later. float distance = bodyToPlanetDirection.Length(); // Normalize turns your vector into a unit vector, which is of length 1 - or one unit. This allows you to multiply it with a fixed factor later on, to create a constant force vector pointing in the direction of the planet. bodyToPlanetDirection.Normalize();
// Real gravity falls off by the square over distance float distanceSquared = distance * distance; // These numbers are arbitrary, feel free to tweak them until you get the result you want. b2Vec2 force = ((1.0f / distanceSquared) * 20.0f) * bodyToPlanetDirection; body->ApplyForce(force, body->GetWorldCenter());
Hope this helps!
Regards, Gabriel Lim
|