Unity2D Check which direction the enemy AI is heading?

Hey I need assistance figuring out which way my AI is going so I can rotate the vehicle if needed.

I tired to us xDir and yDir. The xDir code works great but the yDir code is funky and making the vehicle rotate when going in the x direction.

Here is my code:

using UnityEngine;
using System.Collections;

public class AICarScript : MonoBehaviour {
public Transform[] waypoints;
int cur = 0;

public float speed = 0.3f;

	// Use this for initialization
	void Start () {
	
	}
	void CheckDirection()
	{
	//Declare x and y movement variables. Ranges from -1 to 1
	int xDir = 0;
	int yDir = 0;
	yDir = waypoints[cur].position.y > transform.position.y ? 1 : -1;
	xDir = waypoints[cur].position.x > transform.position.x ? 1 : -1;

		//Check if the car is going left or right
			if (xDir == 1)
			{
			GetComponent<SpriteRenderer>().flipX = true;
			//GetComponent<Rigidbody2D>().rotation = 0;


			}
			else if (xDir == -1)
			{
			GetComponent<SpriteRenderer>().flipX = false;
			//GetComponent<Rigidbody2D>().rotation = 0;

			}

		//Check if the car is going up and down
		if (yDir == 1)
		{
		GetComponent<Rigidbody2D>().rotation = 90;
		}
		else if (yDir == -1)
		{
		GetComponent<Rigidbody2D>().rotation = -90;
		}
		else if (yDir == 0)
		{
		GetComponent<Rigidbody2D>().rotation = 0;
		}


	}
	// Update is called once per frame
	void Update () {

	//Waypoint not reached yet? Move towards it
	if (transform.position != waypoints[cur].position)
	{
	Vector2 p = Vector2.MoveTowards(transform.position, waypoints[cur].position, speed);
	GetComponent<Rigidbody2D>().MovePosition(p);
	CheckDirection();

	}
	///Waypoint reached
	else cur = (cur + 1) % waypoints.Length;

	}
	bool valid(Vector2 dir)
	{
	Vector2 pos = transform.position;
	RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
	return (hit.collider == GetComponent<Collider2D>());
	}



}

Hey @kunald,

You’re just manually changing the y rotation of the AI car to be either 90, -90 or 0. You aren’t += 90, just hard setting it to one of the three. Perhaps try checking out Transform.Lookat() in place of trying to manipulate the y with those values. You could do it every frame, but maybe just try doing it after you set the new waypoint so you only have to do it once.

gameObject.transform.LookAt(waypoints[cur].transform.position);

I hope that helps.

Cheers.