# Train-like movement in a 2D game

I am developing a 2D game using Cocos2d-X in C++ language. In my game, I need to implement train movement.

Here is the image about the output I want to achieve:

I tried to do the above moment using Actions from Cocos2d-X. However on the curved part of the tracks, the train movement is not accurate.

I have following questions:

1. Is there a right method to create the train movement using Actions? If not, which alternate methods or algorithm can be used?

2. I wanted to achieve train movement similar to the game Mini Metro. How to create such train movement in Cocos2D-X?

I would appreciate any suggestions/thoughts on this topic.

• You should add a link to a youtube video, or an animated gif integrated in the question, that shows what you want, i.e. a clip showing how the train moves in Mini Metro. Apr 5 '17 at 11:57
• Code block formatting is for code. Don't use it for text.
– Nic
Apr 5 '17 at 20:10

I'm not used to Cocos2D engine, but I can suggest this solution for you to apply to your game.

Naive implementation
The simplest way to implement a train wagon can be making an object which follows a given path, whose angle rotates according to the path direction. Given a path (as an open line or closed polygon) consisting of a finite number of points, the direction along the path can be computed with the inverse tangent (or any equivalent function) of the two vertices representing the current line segment the train is moving onto.

This leads to an issue: when turning, the wagons will be always centered to the railway track, because we are rotating every wagon object considering its sprite origin only, and we'll see wagons edges too unnaturally distant from one another. Also, if the path quality (aka the number of segments making up our line or polygon) is low, wagons sprite will abruptly change its rotation angle when moving from line segment to line segment.

Improved implementation
Real train wagons are usually bonded to the railway track by two or more couples of wheels; the rotation of every wagon when turning depends on the position of its wheels.

Instead of working with one point only, which represents the center of mass (or origin) of our wagons, we can consider two points per wagon, each one representing the midpoint of every couple of wheels. Such midpoints are here coloured blue:

This way, we force these midpoints to travel onto the railway track, making sure their relative distance never changes, and midpoints belonging to different wagons always keep the same relative distance as well.

The final touch is drawing the wagon sprites with origin in the midpoint between the two previous wheels midpoints, and its rotation angle will be the inverse tangent of the two wheels midpoints as well. The direction will be correct since the midpoints are forced to the path.

Hope that helps you solving your issue, or developing a more appropriate solution on your own.