Search code examples
iphoneobjective-ciosbox2dgame-physics

Box2d - Giving an object attraction / gravity


I am using Box2d to simulate a top-down space like environment. I have an object that has an impulse applied and will be flying (through space) near to a "planet". The world itself has no gravity but I would like to set up Planets and Stars with individual gravity such that other dynamic objects will fall / be pulled in towards them. How can I achieve this?


Solution

  • If you have small count of bodies/stars you can just apply gravity forces to your bodies each time before calling Step() function.

    But I think it will become really slow if the system gets big. If your stars and planets are not moving you are able to precalculate the total gravity force in each point of 2D space. Store this precalculated values of gravity in some 2D array (with some step) and then apply the forces from this lookup table