- Home /
Creating a trail of characters that follow you
Hello all,
I'm looking to prototype a 2D game that has a mechanic where you have a group of characters that follow you around exactly like this: https://youtu.be/2ejnYn7OZxo?t=182 (Flicky, Sega Genesis)
I'm having trouble wrapping my head around how this effect would be best achieved. My first instinct was that I should create waypoints that follow behind the player and have some AI in each follower that tries to stay as close as possible to it's assigned position. But I have a suspicion that there may be a more simple and efficient way to do this that doesn't involve giving each follower separate AI and physics components.
I don't need code snippets, I'm just looking for a general idea of how I could tackle this effect. Thanks in advance!
Answer by V_0_1_D_ · Mar 01 at 06:56 AM
An easy way to do this is using Distance Joint 2D. Consider you have a main object and 4 other objects, that must be followed by them continuously. All 5 objects should have a rigid body 2d attached, 4 others (except main object) must have a Distance Joint 2D. Then in connected rigid body field for each of them in the inspector, you must select the object that MUST be followed, for example, select main object for object 1, object 1 for object 2, etc.
The logic behind this is that any object does not exceed maximum distance with it's following object, which can be achieved manually in code with some effort.
Here is a sample code.
using UnityEngine;
public class FollowTrail : MonoBehaviour
{
[SerializeField] Transform following;
Vector2 currentVelocity;
float maxDistance = 2.0f;
float smoothTime = 0.2f;
private void Update()
{
float distance = Vector2.Distance(transform.position, following.position);
if (distance > maxDistance)
{
transform.position = Vector2.SmoothDamp(transform.position, following.position, ref currentVelocity, smoothTime);
transform.right = Vector2.SmoothDamp(transform.right, following.right, ref currentVelocity, smoothTime);
}
}
}
Your answer
Follow this Question
Related Questions
How To Add A FX When I Teleport. 0 Answers
Is there a working transparent reflective shader avaliable? 2 Answers
Game Lighting issue 0 Answers
does unity 5 pitch shifter audio effect change playback speed? 1 Answer
Blink Emission 0 Answers