0
\$\begingroup\$

I am trying to get enemies to chase player but without them overlapping each other when they get closer to the player.

So far what I have is that I check for the distance between current enemy and the another enemy in a list and if their distance is less than 2 then update their position away from each other.

But when I do that, the enemies instantly move away rather than smoothly moving away from each other. What can I do to improve this?

Here is my script for chasing player:

public void ChasePlayer()
{
    foreach (GameObject enemy in enemies)
    {
        if (enemy != null)
        {
            float currentDistance = Vector3.Distance(transform.position, enemy.transform.position);

            if (currentDistance < 2.0f)
            {
                Vector3 dist = transform.position - enemy.transform.position;
                transform.position += dist;
            }
        }
    }

    if (lantern.transform.GetChild(0).gameObject.GetComponent<Light>().enabled)
    {

        gameObject.GetComponent<MeshRenderer>().enabled = true;
        gameObject.GetComponent<Collider>().enabled = true;
        transform.LookAt(player.transform);
        transform.position += transform.forward * speed * Time.deltaTime;

    }
    else
    {
        gameObject.GetComponent<MeshRenderer>().enabled = false;
        gameObject.GetComponent<Collider>().enabled = false;
    }
}
\$\endgroup\$
0
\$\begingroup\$

I fixed it. All I needed to do was multiply dist by Time.deltatime.

Like so: transform.position += dist * Time.deltatime;

\$\endgroup\$
0
\$\begingroup\$

You could change your approach, and look into using the Unity's NavMesh Agent system instead.

With a nevmeshagent, there is a property on the agent which offsets the character along a vertical axis to get a result you would be looking for.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.