- Home /
Last key pressed
Hey guys^^
I wanted rebuild my 4 way, 2D shooting script, so that it shoots only in the direction where the last key is pressed.
This is what I have so far:
if (Input.GetKey ("down")) {
shotDirection = 1;
}if (Input.GetKey ("up")) {
shotDirection = 2;
}if (Input.GetKey ("left")) {
shotDirection = 3;
}if (Input.GetKey ("right")) {
shotDirection = 4;
}
But with this way, if more keys pressed it takes the last key from the order. I expermented with Event.current.key only to see that Event works only in OnGUI xD
Sadly I have no idea how to solve this :(
Does anyone have some suggestions for dealing with this problem?
Thanks a lot guys :)
I'm not quite sure what you mean by "if more keys pressed it takes the last key from the order". Could you rephrase or eleborate on that?
Oh I'm very sorry my english isn't the best :(
What I mean is: The player press the right key to shoot right and than press the left key. Atm the player would still shoot right and ignors the left key because "if (Input.Get$$anonymous$$ey ("right")) { shotDirection = 4; }" is after "if (Input.Get$$anonymous$$ey ("left")) { shotDirection = 3; }" But I want that the player shoots left because it's the last pressed key.
Now I understand what you meant. I think the answer by EpicPants is the one you'll need to look at. Get$$anonymous$$eyDown() might work better, because users are less likely to press two keys down on the exact same frame. You'll have to keep in $$anonymous$$d though that Get$$anonymous$$eyDown() only returns true in that one frame the key was pressed. So, you'll have to make sure the shotDirection variable keeps it state. You can do that by making it a class variable for example.
Answer by EpicPants · May 05, 2015 at 08:41 PM
GetKey will return true every frame the key is down. If you use GetKeyDown then it will only return true the frame you first press the key. Try using that instead.
It will still take the last key from the order if all statements are true in the same frame, but it will only happen if you press them all at once. Unfortunately I think you need to prioritize directions in this case.
Omg certainly is Get$$anonymous$$eyDown the solution. It was so easy but I still didn't realized it x.x
Anyways thank's alot :)
Your answer
Follow this Question
Related Questions
KeyCode parse problem 0 Answers
String as a input 2 Answers
Key binding screen 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers