- Home /
Determine the direction of a gameobject from vector2 without using if/else?
I have a gameobject in a 2D game that is controlled by a vector2 for the direction it is moving. the values in that vector2 come from input.GetAxis("Horizontal") etc. I need to determine what direction it is moving in from that vector2 (up/ down/ Left/ Right). i could easily use a few if/else statements to figure it out, but it feels like there is a mush easier and more efficient way of doing it. Is there anyone who know of another way or know if if-statements are the way to go? Thanks in advance.
Huh? The Vector2 is the direction it's moving in, surely?
transform.position += direction * speed;
That is how i am moving the gameobject, so yes, that is the direction. The direction is the vector2. it can have a value of -1,0,1 on both x and y. Example: (1,0) will move it straight up.
Right..... so if you agree that you already know the direction, what's your question? You want to translate that into the words "up", "diagonal up-left", "right" etc.?
what states do you want to get into? just might be wrong, but a 2d blendtree could work in your case
i have some states like idle, walking, paused etc, but when i'm in the walking state i have sub states (up, down, left, right). i have the vector2 that technically tells me the direction, but i want to direct the path the code is taking depending on the direction the vector2 is representing. I could use if statements to check what direction it has and then check if the direction has changed since last update, but i feel like there is a better way. I googled blendtree really fast, and that might be something that could work. will look in to that.
Just looked at some totorials on blendtree, and that will work. thank you.
Answer by ifdef_ben · Feb 07, 2017 at 10:43 PM
Well if your are moving your character on the x-z plane then you can most likely simply do:
Vector3 direction3D = new Vector3();
direction3D.x = direction2D.x;
direction3D.z = direction2D.y;
transform.position += direction3D * speed;
That is basically exactly what i have done, but that is not what i need help with. I want another script to know what direction the gameobject is moving. i have come so far that i have basically the same vector2 in that other script, but i want deter$$anonymous$$e the path the code should take depending on the direction that vector2 is representing. As I mentioned earlier, i could check it with if-statements every update, but i feel like there is a better way to do it.
Your answer
Follow this Question
Related Questions
Why doesn't my object move left? 1 Answer
Determine global movement of gameObject 2 Answers
Swipe not 100% perfect 0 Answers
Weird angle returned 1 Answer
Top-Down Enemy Ai Animation 0 Answers