How to make a secondary object mimic and follow a primary object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Corruptinator
:warning: Old Version Published before Godot 3 was released.

This might sound advanced to ask for this but the reason why I like to know this answer whatever it may be is because I am currently working on a short game for a game jam that is going on right now, such as ITCH.IO’s Low Rez Game Jam and the thought in mind I’d like to know is how can I make a secondary object follow a primary object in coding?

This was done on some classical games. For example:

Paper Mario - Mario’s companions follow Mario by a queue system that mimics Mario’s Controls, position, and jumps.

or

Gradius - Where the first enemies of each stage acts like a worm but following the primary leader before it gets destroyed and lets the next enemy in line take the lead and letting the secondary objects follow it?

Does anybody know how this can be done in GDScript? If not, well then I guess it was worth asking…

:bust_in_silhouette: Reply From: kubecz3k

The fastest/easiest way of doing this that I can think of is to simply interpolate object position to target position being behind the leader. Strategy for choosing ‘behind leader’ position is the most crucial part here if you want for your followers to avoid walls and other static obstacles. Idea I have is simple: the position where leader was shortly in the past should be the position that followers will try to get into.
I will write some quick and dirty pseudo-code .

Inside the Leader:

const var MAX_DST = 2.0;
var targetPos4Followers = Vector3();
function process(delta):
   var currentPos = get_translation();
   var dst2FollowersTargetPos = currentPos.distance_to(targetPos4Followers);
   var findNewPos4Followers = dst2FollowersTargetPos > MAX_DST;
   if( findNewPos4Followers):
      var dirBetweenOldTargetAndCurrentPos = (currentPos-targetPos4Followers).normalized();
      targetPos4Followers+=directionBetweenOldTargetAndCurrentPos*dst2FollowersTargetPos/2.0;

I’m assuming 3d here, if you are doing 2d then change MAX_DST to something greater, like double the size of the leader

I am doing this in 2d, the code almost works but how will it find the object within the distance and tell it to go to that position?

Corruptinator | 2016-04-10 04:08

Better yet, How can I actually detect nearby objects with this code?

Corruptinator | 2016-04-10 04:22

The idea/code I provided is not for detecting other objects (it’s not a subject of this question). Basically you can do this on many ways, one of the simplest one would be to use Area node. But I’m thinking it will be the best if you could open new question before we go into this subject, since this way other people will be able to benefit from the question/answer in the future.

kubecz3k | 2016-04-10 18:29