I am trying to disable diagonal movement in a really simple 2D character controller. I have been trying all sorts of things with no real luck at all.
Basically, when two movement keys (i.e. “w” “d”) are pressed at the same time I want the controller to continue along the axis of whichever button was pressed first.
It’s quite easy. You are atm. checking if any of the keys “wasd” are pressed. If you instead use the method:
Input.GetKeyDown()
it will trigger the last keydown instead.
I would recommend that you set up you input in Edit > Project Setting > Input and define your inputs. And after that instead use Input.GetButtonDown() that way you can have more control of your input, instead of defining it as “hard keys” on your keyboard.You could also write less code if you use Input.getAxis() instead and reduce your if-statements to two instead of four.
Thanks for the reply. GetKeyDown and GetButtonDown only return true on the frame that the button is pressed so I guess I am not sure how I would use that in this application.
oh im sorry, it’s me that didn’t read the question well enough. I missed the part that you wanted to disable diagonal movement.
So basically you want only one button to be able to be pressed at any time.
What people usually do is that they create different “states” for their character. you could create 4 four bools that represent character walking left, right, up and down and check if character is walking up, then he can’t be walking left or right or any other direction.
(code made from the top of my head, so might not work properly, but the key here being the “return;”)
by default, Unity has setup WASD as axis in the Input Settings. Added bonus is, this will work with a controller as well
Thanks Toerktumlare, just throwing a “return;” in each if statement seemed to be what I was missing. I imagine I am going to have to create states like you mentioned above also though to handle various character interactions and such.