Open-Source 2D Train Project (Godot 3.5)

Since putting together Littletown Journey, I've kept working on improved locomotive/railroad network and physics logic.

This is an implementation I came up with that feels abstract enough to be useful in other people's projects, so I'd like to share it.

How it works

This is built on top of Path2D and PathFollower2D nodes.

Tracks

A developer working in Godot with this code, can add Track or TrackSwitch nodes to a scene. A Track is a Path2D node with child nodes used for connecting to neighboring tracks, it also has the logic that adds the visual styling.

Track nodes have a head and tail where TrackJunction children sit. These are Area2D nodes and are moved to the first and last (respectively) points in the track's path. They are used to detect the junction nodes of nearby tracks segments to automatically connect them.

Vehicles

The individual TrainVehicle nodes each sit on top of two TrainWheel nodes, which are PathFollower2D nodes.

By placing down track segments and switches, developers can build any sort of track.

Switches

A TrackSwitch node has two Track segments with a shared "head".

When a train vehicle enters either track's tail it will simply ride the track as normal and exit from the head's junction. However, when a vehicle enters from the switch's head node, it will be placed on one track or the other depending on the switch's state.

Note:

This was posted to the Godot Subreddit Choo Choo! Open-source 2D train/railroad mechanism now has brakes, updated sprites, camera control, and a cleaner UI (Link in comments).

Demo & Code

The code and pixel art for this was published on GitHub (and was MIT licensed) so you can easily browse, fork, or download it to use in your own projects.

Published: March 23, 2023

Categories: gamedev