- Home /
How do I translate a vector2 into one of the fixed directions
Hi, Let's say I have some vector2, based on user input.
How do I find the nearest "direction" for that vector?
I would like to get if it's closest to Vector2.left of Vector2.up, as an example.
Is there a trick to this in unity, or do I need to dive into some vector maths?
Answer by rufopufo · Jul 15, 2019 at 10:52 AM
Hi there,
Firsty, you will need to see to what axis, is your vector nearer. You can achieve this, by simply comparing x and y components of your vector in absolute mode.
Example: Vector (0.3,0.7), has a greater y, so the Y axis, will be the nearest.
Vector (-0.4,0.1), has a greater x in absolute mode, so the X axis, will be the nearest.
Having this, you can handle the direction by observing the sign of your vector component.
Example: (-0.4,0.1), we had determine that X axis is the nearest, and the x component is negative. So Vector2.left will be the desired direction.
(0.3,0.7), we had determine that Y axis was the nearest, and 0.7 is positive, so the direction is upwards.
You don't have to really dive into maths, just compare the components of your vector.
Hope it helps. If you need more help, just comment.
Thanks! It's so simple, I guess I was blinded by my own math-failures.
Answer by Ex6tra · May 15 at 01:05 PM
I'll leave this here in case someone comes across this question
Vector2 Snap(Vector2 dir)
{
float absX = Mathf.Abs(dir.x);
float absY = Mathf.Abs(dir.y);
if (absX > absY)
{
return dir.x > 0 ? Vector2.right : Vector2.left;
}
else if (absX < absY)
{
return dir.y > 0 ? Vector2.up : Vector2.down;
}
return Vector2.zero;
}
Your answer
Follow this Question
Related Questions
How to find direction Vector for a collision surface? 1 Answer
Diagonal Movement 1 Answer
Get angle between 2 Vector2's 5 Answers
Get angle of Vector2 1 Answer
the projectile reflects 1 time only when it hits something, pls help! 1 Answer