Paths and multiple linked objects

HayManMarc

Member
Hay, man.

I'm messing around with a little train game idea. I have a train engine following a path. I can speed it up and slow it down, and make it go forward or reverse, all while staying nicely on the path. Works nice.

Now, how do I add a train car to it, that will stay on the path and stay the correct distance away but still look like its connected to the engine?

I don't even know where to begin and just hoping for a nudge in the right direction.
 

Nidoking

Member
You probably want to use some kind of list or queue of points to store the positions where the engine has been and have the car(s) pull positions from it. If you want to be able to reverse, it'll have to be a list.
 

MusNik

Member
Another approach:

If the "head" of your train is moving on path by path_start you could do something like this in the Step event of "car" object
GML:
var path_pos = modulo(obj_head.path_position - obj_head.sprite_width / path_get_length(path), 1);

x = path_get_x(path, path_pos);
y = path_get_y(path, path_pos);

dir_x = obj_head.x - lengthdir_x(obj_head.sprite_width / 2, obj_head.image_angle);
dir_y = obj_head.y - lengthdir_y(obj_head.sprite_width / 2, obj_head.image_angle);
image_angle = point_direction(x, y, dir_x, dir_y);
Also add modulo script for correct negative number mod wrapping:
GML:
/// @function modulo(a, b)
/// @param a
/// @param b
/// @return {real}

var a = argument0;
var b = argument1;

return abs(abs(a) - abs(floor(a / abs(b)) * b));
 
H

Homunculus

Guest
I can see two ways to implement this:

1. All the cars + engine composing a train move "independently" on the path, but all at the same speed (therefore giving the illusion they are actually moving relative to one another)
2. Move only the engine, and have cars follow its coordinates without actually being on the path (as Nidoking suggests).

I'm a bit unsure about what's the better option, but I'd probably go for 1. Treating the whole train as a single unit, although a little counter-intuitive seems like a better solution to me. All you have to do is keep track of the train composition as a collection of cars, but most importantly, ensure you place the instances correctly to begin with relative to each other.
 

Sabnock

Member
Hi Marc,

Just sent you a demo on Discord.

it doesn't use the GMS path_start() but instead uses path_get_x() and path_get_y() and then uses offsets to set the positions of the carriages relative to each other.

1585685983335.png

Code:
var move = keyboard_check(vk_right) - keyboard_check(vk_left);


p_pos += move * .005;

p_pos = clamp(p_pos, 0, 1);

x = path_get_x(path_id,p_pos);

y = path_get_y(path_id,p_pos);

if (xprevious != x || yprevious != y) image_angle = point_direction(xprevious, yprevious, x, y);
Alternatively you could use the physics engine?
 
Last edited:
Top