So I am basically creating a platformer game in java. Here is a simple question. Can I respond to two different KeyEvents simultaneously? For example, I am pressing the right arrow key and my player is moving right. Now, I want my player to jump but keep moving right. For this I would need to respond to two different KeyEvents simultaneously. How do I achieve this? I have not tried any code yet because I don't know where to start with. Thank you for the answer in advance.
You can use seperate "KeyDown" and "KeyUp"-events and set state values for your player.
You need a State-Machine for your player.
public class KeyboardListener extends JFrame implements KeyListener {
public KeyboardListener() {
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key pressed");
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key Released");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key Released");
}
}
public static void main(String[] args) {
new KeyboardListener();
}
}
Use the keyPressed and keyReleased-EventHandlers from the KeyListener Interface and save your current player states like walking, jumping, walk_left, walk_right etc as booleans for example.
In your mainloop you can check what state your player is in and change its coordinates. Like:
if(player.left) { player.x += speed } //etc.
You might want to use Threads and then add pressed keys to a list the player physics class.
public class KeysListener implements KeyListener
...
//FIRST THREAD
new Thread(new Runnable() {
#Override
public void run() {
public void keyEvent(KeyEvent e) {
int key = e.getKeyCode();
//TODO ADD KEY TO A LIST IN THE CLASS THAT HANDLES YOUR PHYSYICS
}
}
}).start();
//SECOND THREAD
new Thread(new Runnable() {
#Override
public void run() {
public void keyEvent(KeyEvent e) {
int key = e.getKeyCode();
//TODO ADD KEY TO A LIST IN THE CLASS THAT HANDLES YOUR PHYSICS
}
}
}).start();
...
}
Add as many threads as the number of simultaneous keys you require.
Related
We areto create a plane and have its speed increase 5mph every time the user inputs the up arrow key and decrease 9mph when hitting the down key. It is supposed it report this back to the user in output box whenever whichever action is completed. How do I set it up so that the keylistener will tell the user that they have pressed the up key? Im still working on this so sorry if it is messy.
private class PolygonPanel implements MouseListener, MouseMotionListener, KeyListener
{
public void mousePressed(MouseEvent event){} //unused event
public void mouseDragged(MouseEvent event){} //unused event
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){}
//public void keyPressed(KeyEvent event){}
public void keyPressed(KeyEvent event) {
Integer planespeed=event.getKeyCode();
if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
//Not gonna use this.
}
if (event.getKeyCode() == 39)//KeyEvent.VK_LEFT
{
System.out.print("This key is up");
}
if (event.getKeyCode() == KeyEvent.VK_UP)
{
System.out.print("This key has been pressed");
//speed=planespeed+5;
}
if (event.getKeyCode() == KeyEvent.VK_DOWN)
{
//speed=planespeed-9;
}
repaint();
}
A frame doesn't detect keybaord input if it is not focused on. Therefore, in order to retrieve keyboard input of any kind, you would have to set your frame to be focusable, using a line such as setFocusable(true); in your constructor. You might also have to add a line such as addKeyListener(new PolygonPanel()); so the listener is registered at all.
I have a Graphics project that contains KeyListener, where the arrow keys and space bar controls the movement of a spaceship. However, when a key is held down, it registers the next key presses after a delay after the first. I would like for a held down key to register continuously.
I suspect that this is due to my computer's setting for key repeat delay, so is there any way to temporarily override this in my program, or a workaround for it?
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 38) { //Up Arrow
currentLevel.moveSpiffUp();
} else if (e.getKeyCode() == 40) { //Down Arrow
currentLevel.moveSpiffDown();
} else if (e.getKeyCode() == 32 && !currentLevel.getFrapRayActive()) {
currentLevel.shoot();
}
repaint();
}
I would suggest using key press and key released
public class MyKeyListener implements KeyListener {
//class gets the input from the player
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(KeyEvent.getKeyText(e.getKeyCode()).equals("Left")) {
//left arrow key
} else if (KeyEvent.getKeyText(e.getKeyCode()).equals("Right")) {
//right arrow key
}
}
public void keyReleased(KeyEvent e) {
if(KeyEvent.getKeyText(e.getKeyCode()).equals("Left"){
//left key released
}
if(KeyEvent.getKeyText(e.getKeyCode()).equals("Right")) {
//right key released
}
}
}
I then used this bit of code in my main constructor
main() {
KeyListener listener = new MyKeyListener();
addKeyListener(listener);
setFocusable(true);
}
This way you wont have your delay when hitting keys.
I'm currently working on a little game. I'm using getKeyCode to move my character but the thing is that I don't want you to be able to keep moving if you hold in the button. Is there anyway I can use getKeyCode to only register on the first click and then won't register until I release the button and press again?
else if (event.getKeyCode()== KeyEvent.VK_UP)
{
spelare1.setLocation(spelare1.getX(),spelare1.getY()-50);
}
This is how it currently looks like.
I think you are confusing KeyEvents. VK_UP is the up arrow key. Use KeyEvent.KEY_RELEASED to react on a released key.
You can keep a boolean indicating whether the key is currently pressed. Then you can react once after each press, like in this example:
public static void main(String[] args) {
JFrame f = new JFrame();
f.addKeyListener(new KeyAdapter() {
private boolean pressed;
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
#Override
public void keyPressed(KeyEvent e) {
if (!pressed) {
System.out.println("Key pressed: " + e.getKeyCode());
pressed = true;
}
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.setVisible(true);
}
});
}
Depending on your needs, you might want to have a separate state for each key, or just one shared state.
I'm programming a game in java that has two players on the same keyboard. If one of the players is holding their forward button and the second player presses his forward button the first player is stopped. This happens the other way around too and I'm not sure how to fix it.
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
paddletwo.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
paddletwo.keyReleased(e);
}
In each paddle class I also have this:
public void keyReleased (KeyEvent e) {
ya = 0;
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP)
ya = -pong.speed;
if(e.getKeyCode() == KeyEvent.VK_DOWN)
ya = pong.speed;
}
Player two uses VK_W and VK_S instead of UP and DOWN.
This is related to the actual hardware keyboard. To reduce costs the control lines are shared so that it's impossible to push a certain combination of keys at the same time.
Either buy a high-end keyboard or choose the keys carefully so there is minimal interference (of course this is harder the more keys you use, and it will result in some funny looking controls).
Here's the reason explained.
Edit:
Actually this shouldn't affect when only 2 keys are involved, only with 3 or more.
Ok, how to i move from keyboard a ball using an Applet?
I have so far this code, that don't do anything.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class KeyboardGame extends Applet implements KeyListener
{
private static final long serialVersionUID = 1L;
private static boolean keyboadrRightPressed = false;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboadrRightPressed = true;
}
else
{
keyboadrRightPressed = false;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void paint(Graphics g)
{
g.fillOval(20,20,20,20);
g.drawString("String :"+keyboadrRightPressed,20,30);
}
}
And also i have to understand how it works. I don't get why my action listener won't work, do i need an
while(true)
or an Thread?
Your action listener might actually be working fine, but you need to repaint the applet when the key is pressed so that your string actually appears. Try changing the keyPressed to this:
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboadrRightPressed = true;
}
else
{
keyboadrRightPressed = false;
}
repaint();
}
Actually moving the ball will differ depending on how you want the ball to actually move. I'm guessing you want it to continue moving right while the key is held down, so what I would do is implement a timer or some other form of thread that every .25 seconds (or however long you want) checks the keyboardRightPressed and will move the ball right if it is true. Then in the keyReleased portion of your code you should also add logic to set keyboardRightPressed back to false when you let up on the key.