# How to know if 2D gameobject is moving left or right?

I have an enemy that is being moved using Vector2.MoveTowards and I want to know how determine if it’s moving towards the negative or positive x-axis. I tried getting its velocity but it only seems to return a positive value.

Thanks, guys!

Hi, to check which direction it’s moving in in 2D, you’ll check for changes to it’s x transform.position value.

So in code it might look like:

``````Vector2 posLastFrame;
Vector2 posThisFrame;
void Update()
{
posLastFrame = posThisFrame;

posThisFrame = transform.position;

CheckMoveDirection();
}

enum Direction { Right, Left, Still };
Direction CheckMoveDirection()
{
if (posThisFrame.x > posLastFrame.x)
return Direction.Right;
if (posThisFrame.x < posLastFrame.x)
return Direction.Left;
else
return Direction.Still;
}
``````

You could do something like…

Vector2 oldLocation;
Vector2 newLocation;

oldLocation = newLocation;
newLocation = gameObject.transform.blahblah;

Do some fancy math, to determine if it’s negative…or positive.

Check this link For Left or Right if going determin to gameObject