- Home /
How to make enemies take wider routes?
I'm currently using A* pathfinding to mainly control my enemy's movement, however, I'm having a problem with it being constantly in contact with the collider, and it struggling to get around the corners. I would make the margins wider, but the problem there is that its destination is next to the collider, so that's not an option. The yellow boxes in the image are the potential destinations. Any advice or ideas? Thanks in advance!
Answer by blinkafrootable · Jul 26, 2019 at 02:56 PM
I suggest that you change the A* algorithm to not allow diagonal movement if there is an object adjacent to the enemy. This image demonstrates what I'm talking about: If you're wondering how exactly you might implement that in code then I'd like to see the code you used for the algorithm.
I thought unticking cut corner was supposed to do that? Regardless, here's the part of my code that uses A*:
using UnityEngine;
using Pathfinding;
public class Temp : $$anonymous$$onoBehaviour
{
//pathfinding variables
Seeker seeker;
public Path path;
public float nextWaypointDistance = 3;
private int currentWaypoint = 0;
public bool reachedEndOfPath;
Vector2 dir;
public float pathUpdateRate = 2f;
//cover-checking variables
Collider2D[] coversNearby = new Collider2D[50];
Collider2D closestCover;
float closestCoverDistance = 15f;
public static bool inCover;
void Update()
{
if (path != null)
{
reachedEndOfPath = false;
float distanceToWaypoint;
while (true)
{
distanceToWaypoint = Vector2.Distance(transform.position, path.vectorPath[currentWaypoint]);
if (distanceToWaypoint < nextWaypointDistance)
{
if (currentWaypoint + 1 < path.vectorPath.Count)
{
currentWaypoint++;
}
else
{
reachedEndOfPath = true;
break;
}
}
else
{
break;
}
}
dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
}
}
void FixedUpdate()
{
if (closestCover != null)
{
rb2d.AddForce((dir) * movementSpeed);
}
}
void GetClosestViableCover()
{
closestCoverDistance = 15f;
int numberOfCovers = Physics2D.OverlapCircleNonAlloc(transform.position, 15f, coversNearby, mask2);
for (int i = 0; i < numberOfCovers; i++)
{
float distanceFromCover = Vector2.Distance(coversNearby[i].transform.position, transform.position);
if (distanceFromCover < closestCoverDistance)
{
closestCoverDistance = distanceFromCover;
closestCover = coversNearby[i];
seeker.StartPath(transform.position, closestCover.transform.position, OnPathComplete);
}
}
}
public void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
}
Where in your code is the boolean cut corner
implemented? I don't see anything that indicates that the code checks to see if adjacent waypoints are open
Your answer
Follow this Question
Related Questions
A* - Enemy Pathfinding away from Player 0 Answers
Why is my gameObject falling so slow? 1 Answer
Enemy follow script without rotation 1 Answer
How to I make FindGameObjectWithTag() not just find itself? 1 Answer
Inaccurate A* Pathfinding Scan! 3 Answers