- Home /
2D AI follow issues
Hi guys! I'm creating a 2d platformer with two playable characters (a character and his shadow) and right now I'm prototyping the AI follow behavious for the shadow. Eventually I will create a system for being able to toggle control between them, but for now, I'm just figuring out this part.
Currently I have a script on the player for basic movement:
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
transform.Translate(horizontal * moveSpeed * Time.deltaTime,0,0);
}
And one on the shadow for following the player:
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void Update()
{
if (Vector2.Distance(transform.position, target.position) > followDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
The MoveToward is working pretty well, but it's not exactly the behaviour I was looking for. Right now it follows the player nicely, but if the player changes direction it becomes a "push" rather than a "follow" situation because they're colliding with each other. I tried playing with the z positions and sorting layers but none of that really changes the collision situation. I'm still new to this, especially 2D. Please let me know if I've left out any information you need in order to help me troubleshoot this.
Any tips for how I can allow the sprites to pass each other so it can continue following even when the direction changes?
Your answer
![](https://koobas.hobune.stream/wayback/20220612231028im_/https://answers.unity.com/themes/thub/images/avi.jpg)