Home > other >  Enemy Pathfinding with A* (AStar) & Unity
Enemy Pathfinding with A* (AStar) & Unity

Time:03-29

How do I make an enemy stop at a certain distance from the player rather than going right to it? I want to create a ranged unit. I can do the enemy attacks, I just don't want the enemy to go directly to the player. I have a custom AI script on my enemy using the AStar pathfinding package -

    Transform target;

    public float speed = 200f;
    public float nextWaypointDistance = 3f;

    public Transform enemyGFX;

    Path path;
    int currentWaypoint = 0;
    bool reachedEnd = false;

    Seeker seeker;
    Rigidbody2D rb;
    
    void Start()
    {
        seeker = GetComponent<Seeker>();
        rb = GetComponent<Rigidbody2D>();
        target = GameObject.Find("Player").transform;

        InvokeRepeating("UpdatePath", 0.0f, 0.5f);
    }

    void UpdatePath() 
    {
        if(seeker.IsDone()) {
            seeker.StartPath(rb.position, target.position, OnPathComplete);
        }
    }

    void OnPathComplete(Path p) 
    {
        if(!p.error) 
        {
            path = p;
            currentWaypoint = 0;
        }
    }
    
    void FixedUpdate()
    {
        if (path == null) return;
        if(currentWaypoint >= path.vectorPath.Count)
        {
            reachedEnd = true;
            return;
        }
        else 
        {
            reachedEnd = false;
        }

        Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
        Vector2 force = direction * speed * Time.deltaTime;

        rb.AddForce(force);

        float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);

        if(distance < nextWaypointDistance) currentWaypoint  ;
    }

}

All help is greatly appreciated!

CodePudding user response:

The correct way would be to not search for a specific node, but any node within some distance from the target, or any node within some distance and with a direct line of sight.

It looks like the AStar pathfinding library should have functions for things like that. There is for example a GetNearest overload that takes a constraint that might work. Or the maxNearestNodeDistance field. But I'm not familiar with that library, so I have difficulty providing specific suggestions.

Another alternative would be to just write your own implementation. This is not trivial, but also not overly complex, and there are plenty of resources explaining algorithms like A*. You will probably not reach feature parity with a commercial library, but you might only need fairly simple functionality. It might also be useful as a learning exercise to get better knowledge on how AI and path finding works.

  • Related