When I write games I have always something following something else. Camera follows hero. Light follows ghost. Goody follows space ship. Weapon follows player. And so on and so on. This is a very common pattern in my opinion. I do like to show you how to do it with an entity component system. Show you the beauty and reusability of this pattern.
In object oriented way you would give the items to the corresponding object somehow by reference or something. In an entity component system you go the other way around the items does have a link to the object they shall follow. Once you have your system which makes it happen, that every item entity with a link to an other entity will follow that other entity you will be able to let nearly every thing follow anything else.
The objects which leads and those which follow need a position component, if we take the invader game in my previous posts the position component would look like this
Now the object which shall follow an other object needs a link component
I basically just store the entity id I want to follow and that's it. Now we need a system which handles the linked objects. I will have to take care for all entities with a position and a model component and all entities with a position, link and model component. I will call them leaders and followers. The leaders I do manage localy in a hash map to have a fast lookup of entities.
The followers will be iterated and checked if they have a link to one of the followers. The code might look like this. We can argue about the namings I use here but I guess the idea is clear.
The problem with that is that it follows to narrow. That can be enough if you have goodies inside spaceships which will fall down if you destroied that spaceship, but not if for example a light follows our hero. So we need some kind of an offset which we will also take in account.
The offset component looks like this
The follower will also have now an offset, so we can slightly improve the follower set
And the follow algorithme must be extended to add the offset to the leaders position
and we are done.
Of course we could now also make that entity rotate around the leader, so you would have kind of a rotation system which rotates that offset vector. Also you could take in account the direction of the leader for example if the follower is a sword. So from this point on you can make a lot of improvements.