0
\$\begingroup\$

I want to implement an AI behavior where an enemy runs towards the player while sidestepping randomly and aggressively (like in this video: https://www.youtube.com/watch?v=35Ut_C4eL40)

Currently I am just using Vector3.MoveTowards but that results in smooth movement which isn't exactly what I need. I've tried adding an offset to the target using Random.insideUnitCircle but it just doesn't work.

If anyone could give me an algorithm to implement it'll be great. Thanks

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

There are lots of ways you could accomplish this, I'll just give you one to get started.

Attach this script to a gameobject, and give it another gameobject as target to follow. Uncomment line 29 if you're using a top-down view.

using UnityEngine;

public class AssassinMove : MonoBehaviour
{
    public Transform target;
    [Range(0, 10)] public float speed;
    [Range(0, 10)] public float dodgeSpeed;
    public bool assassinMove;

    void Update()
    {
        if (assassinMove)
            MoveAssassin();
        else
            MoveNormal();
    }

    void MoveNormal()
    {
        transform.position =
            Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }

    void MoveAssassin()
    {
        //get a random direction
        Vector3 r = Random.insideUnitCircle;    //for 2D
        //for 3D top down, you need to swap the x and z components
        //r.Set(r.x, 0, r.y);

        transform.position =
            Vector3.MoveTowards(transform.position, transform.position + r, dodgeSpeed * Time.deltaTime);
        transform.position =
            Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
}

That will get you some very random jittery movement, not dissimilar to the assassin, but not the same.

The next question is how to make the movement look good and work how you're picturing it. That's an entirely separate issue, but some ideas:

  • Restrict the dodge vector to a perpendicular vector so it's only a sidestep. (r = Vector2.Perpendicular(v))
  • Run the dodge separately in a coroutine so it only dodges every so often, instead of every frame
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .