I have a simple Mario game and have key events that decide different animations and movements of the player.
They are:
Move Left
Move Right
Jump Left
Jump Right
As you can imagine, the player will only be able to play the jump right animation if he is moving right and is/has pressed the jump button
The issue I have come across is that only 1 key value may be sent at once. This makes if statements with && conditions useless.
Here was the code that did not work:
if(key == KeyEvent.VK_LEFT) {
if(distanceTraveled<300)dx=-5; else dx=-4;
if(key == KeyEvent.VK_UP)
player = jump_L_anim.getImage();
else
player = walk_L_anim.getImage();
} else {
if(distanceTraveled<300)dx=5; else dx=4;
if(key == KeyEvent.VK_UP)
player = jump_R_anim.getImage();
else
player = walk_R_anim.getImage();
}
Simple enough, I realized that there are solutions to this and began attempting to figure out the key pressed before the current one.(this key could not be equal to the one currently pressed).
This would allow an if statement such as
if key==right && lastKey == up
run jump_R animation
I managed to be able to grab the last key, but not the last key that was not a repeat.
I felt really confused and decided to watch this missile guidance for dummies video. That made me even more confused, In my boring accounting class I figured out the solution must be to store all previous values in an array, then I would loop through the values from the last to the beginning. I would continue this until the numbers would not continue. The number where the repetition stops is the last value i am looking for.
For anyone confused by this take a look at these console readings of key movements
48
48
48
49
49
49
49
47
47
47
The number I am looking for in this situation is 49. That is because it was the last key pressed that is not the current key.
Is my logic behind this issue correct? How would you solve this issue? I prefer not working with arrays if there is a simple variable only solution available. I am looking for the fastest and most efficient logic.
Perhaps you can store which keys are held down at the moment into an HashSet, and the if statement would be something like:
if (keyCodeSet.contains(x) && keyCodeSet.contains(y))
where x and y are the key numbers you want. When the keys are released, you simply remove them from the set.
You should keep track of when the keys are released. If up is never released, you know it's still being held. If right is never released, you know it's still being held. Each update, you can check if both are down and react accordingly.
It's actually totally simple:
Listen to both keyPressed and keyReleased
use a Set<Key>1 or just 4 variable for the keys you're interested in
when a key gets pressed set, add it to the set
when a key gets released, remove it
On any key press, check if the other key is there. This way you can distinguish "Up+Right" from "Right+Up" if you want to.
1 Key may be Integer or whatever representation you prefer.
Related
I am trying to make a game where playerOne uses the left shift key in order to make his move (complete his turn), and playerTwo uses the right shift key. However, when making a small program for testing, I've created a KeyEvent object and used getKeyLocation() along with an if statement, but sadly, to no avail.
I'm building an application on Processing using NyARToolkit, but my question is not directly about NyArToolkit but about a key released() method.
The thing is, I show a card and then I can do a few things if I press different keys. I press "X" and it shows one thing, I press "Y" and it shows another thing. The problem is, it shows the info from the last key pressed all the time.
If I change my AR card, it will immediatly show the info from the last key pressed. I would like to do something to release the key, something like: just show while i'm pressing the key, or have an "ESC" to stop showing everything.
I've been reading about the keyreleased() method but I didn't figured it yet out to put it to work.
By the way my method is like this:
if(key == "c") then
else if(key =="d") then...
How about a boolean keeping track wether you've pushed something
private boolean buttonIsPressed = false;
and inside your keyPressed
buttonIsPressed = true;
and inside your keyReleased
buttonIsPressed = false;
This way you can keep track wether it's pressed or not, using a String you can also keep track which button is being held by initializing it in your keyPressed and making it null in your keyReleased.
If I missunderstood your question let me know.
EDIT:
Reading your edit, you're making quite a big mistake there, make sure to use .equals to compare strings so if(key.equals("c"))
Again, your question is not quite clear for me, so if I'm wrong, excuse me.
If I held down the keys up and down, and pressed a button that calls Display.update and ran the following code:
while (!Keyboard.isKeyDown(Keyboard.KEY_SPACE);
Display.update();
boolean up = Keyboard.isKeyDown(Keyboard.KEY_UP);
Thread.sleep(500);
boolean down = Keyboard.isKeyDown(Keyboard.KEY_DOWN);
if (up && down)
System.out.println("Both keys detected");
What would be the outcome? I'm not sure if I should check for all the keys at once during the game update or just when I need them.
I don't understand your question at all but ill try to answer. I have no idea how or where you update your keys, but if you update your key listener, then your program will check if the booleans are true or false. I think you need to learn some basic java before going on to OpenGL because this is a question someone with less than a couple weeks of coding experience would ask. Also, its relative not relitive.
i think it is not relative to Display.update as it is not logical to hold all the booleans for the keys and update the every half a millisecond.
there for i say it is independant of Display.Update
I'm a beginning computer science student and we've been asked to complete a project that animates random generated car objects moving to randomly generated parking spots on a city map grid. I've developed a GUI for the buttons, text fields, and text areas. Everything works as required except for at the end of the animation, when all cars have reached parking spots, I need to display analytics in my JTextArea. My buttons are set up properly and I will show you where the code takes place below:
else if (e.getSource() == start) {
setAnimate(true);
if(simulator.simulationFinished()) {
createAnalytics();
}
}
So here I have implemented an action listener on the button "start" that begins the animation. Currently it:
currently it begins the animation and all the cars travel to the parking spots as intended.
it displays analytics that are derived from before the animation began (Analytics include: car ID, number of moves, average number of spots tried, average distance travelled)
then the animation will conclude.
If I press the start button again it will display the proper analytics.
I know that in order for the program to display the right analytics the moment the program finishes I most likely need a while loop, however I haven't been able to dream anything up that will not create an infinite loop and require me to manually terminate the program via console.
while(!simulator.simulationFinished()) {
if(simulator.simulationFinished() == true)break; {
createAnalytics();
}
}
I've also tried this among several hundred other variations of all the loops in existence. Following from my logic, I need the while loop so that it will keep checking to see if the simulation is finished so that I can execute my method that generates analytics, but if don't give the while loop something to do it just goes on forever and crashes. I'm at a loss, any help would be appreciated. Thanks.
First: no, you don't need a while loop necessarily. You could use the observer pattern instead (for example) and your object would be notified as soon as the simulation had finished. As to your question: the if inside the while is obviously superfluous (as is the == true). The real problem seems to be that simulator.simulationFinished() never returns true. Could you post the code of that function and the code (and any code that directly influences the return value of it)?
Without going into details, there's a serious problem with your while loop.
See, it loops as long as simulator.simulationFinished() returns false.
However, within the loop, you check for the opposite - which will never happen.
I would recommend using listeners of some sort, although the requirement is not clear enough for me to advise any further.
I want do develop a little game in java and swt.
For this reason, I have to react to KeyEvents.
How can I check if e.g. the up arrow key and 'q' are pressed together?
Thanks in advance
phineas
SWT does not have a concept of pressed together (unless you are talking about standard modifier keys such as shift, alt, etc). What you can do is catch both the up arrow and 'q' key events separately. If timing is an issue then you can compare the two time stamps (There is a time field in KeyEvent) and determine what your definition of together is (50 ms? you may want to experiment).
If q is being used like a modifier then this is easier because you can set a flag when q is pressed and when the up arrow is pushed you can check whether the q flag is set. This would be much easier than worrying about timing. Of course don't forget to clear the q flag when the key is released.
Actually, you can implement that. Each key down and key up has it's own event fired, so you know exactly what keys are being pressed when and what keys are down at any moment.
Example: When the down arrow's key down event is fired, you start moving the right paddle down. When the X key's key down event is fired you start moving the left paddle down. When the X key's key up event is fired, you stop moving the left paddle, and when the down arrow's key up event is fired, you stop moving the right paddle. => You control them independently of each other.
You can wrap all that in some sort of utility that will make the solution cleaner.
rancidfishbreath's solution will work. For an excellent example, see http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet25.java
Thanks for your answers!
I just thought I could develop a little pong game quite fast, but I didn't kow key bindings are so difficult to handle! The main obstacle is that the two paddles must be moved in an independent way (currently the pressing keys interfere the opponents moves and vice versa).