I am using A* Pathfinding Project: https://arongranberg.com/astar/ free version in Unity.
My problem is with moving enemy with my script, it shows path correctly in gizmo, but my enemy is not following it. It seems to be aiming to player. The image below shows that it is trying to go through Ground.
Pathfinding.Path path;
int currentWaypoint = 0;
bool reachedEndOfPath = false;
Seeker seeker;
protected Rigidbody2D rb;
protected virtual void Start()
{
seeker = GetComponent<Seeker>();
player = GameObject.FindGameObjectWithTag("Player");
InvokeRepeating("UpdatePath", 0f, .5f);
isAlive = true;
}
void UpdatePath()
{
if (seeker.IsDone())
{
Vector2 playerPosition = target.position;
Vector2 targetPosition = new Vector2(playerPosition.x, playerPosition.y + offset);
seeker.StartPath(rb.position, targetPosition, OnPathComplete);
}
}
void OnPathComplete(Pathfinding.Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
void Update()
{
if (path == null)
return;
Debug.Log("Waypoint position: " + (Vector2)path.vectorPath[currentWaypoint]);
Debug.Log("Enemy position: " + rb.position);
if (currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfPath = true;
return;
}
else
{
reachedEndOfPath = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
if (!canAttack && isAlive)
{
rb.velocity = new Vector2(direction.x * speed, direction.y * speed);
//Vector2 force = direction * speed;
//rb.AddForce(force);
}
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
}
enter image description here
I have seen some articles on the Z axis issue.
I tried to set the position.z of way point and enemy is zero but it didn’t work.
New contributor
DucAnh_Ng is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.