#2D pathfinding script
1 messages · Page 1 of 1 (latest)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform target;
public float speed = 200f;
public float nextWaypointDistance = 3f;
int currentWaypoint = 0;
bool reachedEndofPath = fasle;
Path path;
Seeker Seeker;
Rigidbody2D rb;
void Start()
{
Seeker = Getcomponent<Seeker>();
rb = Getcomponent<Rigidbody2D>();
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)
{
reachedEndofPath = true;
return;
} else
{
reachedEndofPath = 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++;
}
}
}
The bug