A* Pathfinding for Top Down project, how do I make enemyAI to rotate towards waypoints?
Hi I've been trying to figuring this out for 4 hours non stop about trying to rotate an enemy towards a waypoint. This is for my University assignment.
Most of us know A* Pathfinding, this is my first time using it with custom script followed from brackeys tutorials. Everything works great! Until I reach the point where I need to make the enemy AI face the direction it is going. Like facing towards the "generated" path instead of the player. So here's the script. Forward thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class AIPathfinder : MonoBehaviour
{
public Transform player;
public float speed = 200f;
public float nextWaypointDistance = 3f;
Path path;
int currentWaypoint = 0;
bool reachedEndOfPath = false;
Seeker seeker;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
player = GameObject.FindGameObjectWithTag("Player").transform;
}
public void UpdatePath()
{
if(seeker.IsDone())
seeker.StartPath(rb.position, player.position, OnPathComplete);
//(This is where the rotation)
Vector3 toTargetVector = player.transform.position - transform.position;
float zRotation = Mathf.Atan2(toTargetVector.y, toTargetVector.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, zRotation));
}
void OnPathComplete(Path p)
{
if(!p.error)
{
path = p;
currentWaypoint = 0;
}
}
// Update is called once per frame
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++;
}
}
}
Your answer
Follow this Question
Related Questions
astar pathfinding with groups 0 Answers
How do I make AI objects not walk on top of each other? 5 Answers
Trying to add a tracker to enemy AI either prefab or with reference 0 Answers
align player to object location in C#? 0 Answers
Script attached to An enemy but dosent work right if there are multiple enemies. 2 Answers