- Home /
Question by
K-bomb07 · Apr 11 at 08:23 AM ·
2daipathfindingturn-basedastar
Astar Pathfinding ai moves more nodes than it should
Hi, I am trying to make a grid-based ai for a 2D turn based game using AronGranberg's Astar unity package and the unity pathfinding extension. The ai moves in a grid, but it will skip a node sometimes and move 2 nodes instead of 1. I want it to only move 1 node during its turn.
here are my grid settings.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class enemyAi : MonoBehaviour {
public Transform target;
public float speed = 400f;
public float nextWaypointDistance = 3f;
Path path;
int currentWaypoint = 0;
bool reachedEndOfPath = false;
Seeker seeker;
Rigidbody2D rb;
gameManager gameMan;
public float stoppingDistance;
GraphNode node;
// Start is called before the first frame update
void Start()
{
gameMan = FindObjectOfType<gameManager>();
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("updatePath", 0f, 0.5f);
}
void updatePath()
{
if (seeker.IsDone())
{
node = AstarPath.active.GetNearest(transform.position).node;
seeker.StartPath(rb.position, target.position, onPathComplete);
}
}
void onPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
// Update is called once per frame
void FixedUpdate()
{
float distanceFromTarget = Vector3.Distance(gameObject.transform.position, target.position);
if (path == null)
{
return;
}
if (currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfPath = true;
return;
}
else
{
reachedEndOfPath = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint]);
Vector2 force = direction * speed * Time.fixedDeltaTime;
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (gameMan.isPlayerTurn == false)
{
rb.MovePosition(direction);
if (distance < nextWaypointDistance)
{
rb.velocity = Vector2.zero;
gameMan.isPlayerTurn = true;
}
}
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
}
}
and this is my ai script.
If you know why the ai is doing this, I would appreciate a reply.
settings.png
(22.9 kB)
Comment