0
\$\begingroup\$

I am currently using A stars' pathfinding code here: https://arongranberg.com/astar/. So I didn't create any scripts, and used the scripts provided by astar. But the problem here is that even though my player is very far away from my enemy, the enemy will still move towards the player, which is something I don't want. I want the enemy to only move towards the player once the player is a certain distance from the enemy. Also, I am working in unity 2d. Can anyone help me make a code for this? Edit: I have made a script that makes the enemy pathfind using Brackeys tutorial, and then I manually added a code that checks the distance between the player and the enemy, and if the distance is something like 20f, then force will be added to the enemy. But somehow it still doesn't work, so here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;

public class EnemyAI : Enemy
{
    public Transform target;
    public Transform eagle;

    public float PlayerToEnemyDistance;

    public float speed = 200f; //speed of eagle
    public float nextWaypointDistance = 3f; //the distance of the next waypoint

    Path path; //the current path we are following
    int currentWaypoint = 0; //the current waypoint along that path we are targetting
    bool reachedEndOfPath = false; //checks whether the eagle has reached the end of path or not

    Seeker seeker; //references our seeker script
    private Rigidbody2D rb;

    void Start()
    {
        seeker = GetComponent<Seeker>(); //referencing seeker script
        rb = transform.GetComponent<Rigidbody2D>(); //referencing rigidbody
        InvokeRepeating("UpdatePath", 0f, .5f); //allows the eagle to keep generating path
        rb.gravityScale = 0.000001f;
        speed = 0f;
    }

    void UpdatePath()
    {
        if(seeker.IsDone()) //so what multiple paths won't be generating at once
            seeker.StartPath(rb.position, target.position, OnPathComplete);
        //generates a path
        //first word in bracket is starting position
        //second word in bracket is ending position
        //third word in bracket is a function we call after we finish calculating the path
    }

    void OnPathComplete(Path p) //generate a path called p
    {
        if (!p.error) //if we didn't get an error for the path
        {
            path = p; //set current path to newly generate path called p
            currentWaypoint = 0; //resets progress along the path
        }
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        PlayerToEnemyDistance = (target.position.x - eagle.position.x);
        //cheks the distance between the player and eagle

        if (path == null) //if there is no path, return
            return;

        if (currentWaypoint >= path.vectorPath.Count) //checks whether eagle has reached the end waypoint
        {
            reachedEndOfPath = true; //reaches end of path
            return;
        }
        else
        {
            reachedEndOfPath = false; //doesn't reach end of path
        }
        //get the direction of the next waypoint along our path
        Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
        Vector2 force = direction * speed * Time.deltaTime;

        if(PlayerToEnemyDistance <= 30)
        {
            rb.gravityScale = 0f;
            speed = 300f;
            rb.AddForce(force); //adds force
        }


        //the below line checks the distance of the next waypoint
        float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);

        if(distance < nextWaypointDistance)
        {
            currentWaypoint++;
            //we have reached our current waypoint and ready to move on to the next one
        }

        if (rb.velocity.x >= 0.01f) //flip sprites
        {
            eagle.localScale = new Vector3(-1f, 1f, 1f);
        }
        else if (rb.velocity.x <= -0.01f) //flip sprites
        {
            eagle.localScale = new Vector3(1f, 1f, 1f);
        }
    }
}

\$\endgroup\$
1
  • 1
    \$\begingroup\$ How do you currently tell the enemy to move toward the player? Assume users here have never seen the particular A* implementation you're using, and show us enough detail of your scripts and Inspector set-up for us to advise on what you need to change. \$\endgroup\$
    – DMGregory
    Mar 12, 2020 at 11:09

1 Answer 1

0
\$\begingroup\$

So you're telling us that the AStar pathfinding is 'always active'

In this AStar module you mention, there will undoubtedly be some way to turn it on and off for individual entities (enemies) it is attached to.

What you need to do is twofold.

  1. Create a 'trigger' for activating the pathfinding for an individual enemy
  2. Activate the pathfinding.

For 1. I recommend that you either do a simple distance check for now, in that the enemy checks his distance from the player, then if the player is within a certain distance, trigger the pathfinding to begin, and stop the distance checking.

  • you could improve this at a later date by using collision overlap events, which are usually a feature of many physics simulations in common engines.

For 2. it will be up to you to look through the code of the module, ask for support or look at documentation to find out how to enable and disable the pathfinding.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Just did what you said, made my own line of code that pathfinds, and then only add force to the enemy when player and enemy's distance is less than 30, but it somehow still doesn't work. I edited the original text and added the code there so you can see it. \$\endgroup\$
    – user136618
    Mar 12, 2020 at 14:17
  • \$\begingroup\$ Ok. I don't know the module code, and I can't very well tell where I should be looking in your code. I think you very likely have a logical error somewhere, so you should be debugging this yourself. \$\endgroup\$
    – Natalo77
    Mar 12, 2020 at 15:43
  • \$\begingroup\$ A cheap way of solving this would be to limit the max path length the algorithm can find. No idea how to do that for an unknown asset with no source code... \$\endgroup\$
    – Basic
    Mar 2, 2022 at 18:20

You must log in to answer this question.