Search code examples
c++game-enginegame-physicsbox2dphysics-engine

Restrict objects to path in Box2D


Is it possible to restrict objects in Box2D to a path?

Specifically I'd like to move cars around something like a roller coaster and use Box2D for physics and collision detection.

Would this be feasible?


Solution

  • It is possible to restrict objects to paths in Box2D, yes.

    Here are some ways to achieve this where the second way is closer to what you're specifically looking for:

    • Using a joint. The prismatic joint (using b2PrismaticJointDef) will provide a straight line path. Example uses can be found in Box2D test bed code like slider_crank_1.cpp and slider_crank_2.cpp. Meanwhile, the distance joint (b2DistanceJointDef), can be used to keep an object on circular paths. Similarly, other joints will restrict an object to paths according to their purpose and configuration.
    • Using other objects to act like walls for the path. Examples of this can be found in the Box2D character_collision.cpp test bed code.