- Home /
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!
Answer by Cynikal · Jul 25, 2015 at 06:46 AM
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.
Answer by Maynk · Nov 30, 2020 at 04:28 AM
Check this link For Left or Right if going determin to gameObject
: https://forum.unity.com/threads/left-right-test-function.31420/
I hope you give Answer
Answer by FeedMyKids1 · Nov 30, 2020 at 07:07 AM
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;
}
Your answer
Follow this Question
Related Questions
How good is to put Move.Towards on Fixed Update? -1 Answers
MoveTowards is moveing my object to random position when i click it is already on a way 1 Answer
Make object jump to fixed y position 1 Answer
Different velocity to X and Y in MoveTowards 0 Answers
Script click to move not working, MoveTowards always move forward 3 Answers