Search code examples
cocos2d-iphonecocos2d-android

How do create a top view of a train on the tracks with the Box2D physics engine?


I think it would be fun to model a top view of a train following a track, traversing switches and so on, using a physics library like Box2D. What joints and motors would I need to make this work?

I'm curious about how to implement the forces needed to make the car follow a spline track so it can bump into other train cars, pedestrians, DeLoreans etc. Just saying "the car is now at spline(t)" for each time step would create excessive forces in the physics engine. If I understand correctly, you have to stick the car onto the track with one force, constrain its angle to tend towards parallel with the track with another (or stick the front and back of the car to the track with two forces), and create another force to propel the train forward. I'm looking for some details on how to accomplish these things.


Solution

  • For 2D top-down view of a train using a physics engine sounds like serious overkill. The only noticeable effect you'll be seeing from using physics is how individual cars bump into one another as they accelerate or slow down. These forces could easily cause hard to balance effects on the whole train, making it jump, jitter or possibly derail (or, if you force them onto the track no matter what, cars most certainly will not observe the laws of physics).

    The joints from car to car are designed to keep them at a fixed distance, and there's really very little room for cars in a train to move back and forth compared to the overall length of a train. To make a 2D top-down view of a train mostly realistic, you really only need to model these car-to-car interactions as the train accelerates or stops. And that IMHO is better done without a physics engine since it's just a matter of delayed acceleration with a min-max distance threshold of how close or far the cars can be from one another.