0

So I am trying to figure out how to make my ship object to rotate and move backwards/forward simultaneously. I did some research and it says I should use boolean to make the KeyListener to accept more than 1 key pressed at the same time. But when I tried it, it doesn't allow me to do 2 things at the same time. It replaces the old key I was holding on with a new one. Here is my code....

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class ControlledObject extends SimpleSpaceObject implements KeyListener{

public ControlledObject(Point[] inShape, Point inOffset, double inRotation) {
    super(inShape, inOffset, inRotation);
}


boolean KeyHeld = false;

public void PressedW(boolean keyW)
{
    double RotateX = Math.cos(Math.toRadians(super.shape.getRotation()));
    double RotateY = Math.sin(Math.toRadians(super.shape.getRotation()));

    if(keyW)
        super.shape.move(2*RotateX,2*RotateY);
    else
        super.shape.move(0,0);
}

public void PressedD(boolean keyD)
{
    if(keyD)
        super.shape.rotate(5);
    else
        super.shape.rotate(0);
}

public void PressedA(boolean keyA)
{
    if(keyA)
        super.shape.rotate(-5);
    else
        super.shape.rotate(0);
}

public void PressedS(boolean keyS)
{
    double RotateX = Math.cos(Math.toRadians(super.shape.getRotation()));
    double RotateY = Math.sin(Math.toRadians(super.shape.getRotation()));

    if(keyS)
        super.shape.move(-2*RotateX,-2*RotateY);
    else
        super.shape.move(0, 0);
}

@Override
public void keyPressed(KeyEvent e) {
    KeyHeld = true;
    if(e.getKeyChar() == 'w')
        PressedW(KeyHeld);
    if(e.getKeyChar() == 'd')
        PressedD(KeyHeld);
    if(e.getKeyChar() == 'a')
        PressedA(KeyHeld);
    if(e.getKeyChar() == 's')
        PressedS(KeyHeld);
}

@Override
public void keyReleased(KeyEvent e) {
    KeyHeld = false;
    PressedW(KeyHeld);
    PressedD(KeyHeld);
    PressedA(KeyHeld);
    PressedS(KeyHeld);
}

@Override
public void keyTyped(KeyEvent e) {
}
}

I know that the code is not perfect but I am trying to work 1 thing out at a time.

NoobestPros
  • 65
  • 2
  • 8
  • 2
    In `keyReleased`, you are not testing which key was released and are resetting ALL of them. Instead, when a key is pressed, set it's flag to `true` and when released, set it's flag to `false`. Then use a up-date loop to make the decisions about what those flags actually mean... – MadProgrammer Mar 26 '15 at 23:44
  • http://stackoverflow.com/questions/2623995/swings-keylistener-and-multiple-keys-pressed-at-the-same-time – Sdyess Mar 26 '15 at 23:45
  • Method names should NOT start with an upper case character. Show me a method name is the Java API that does start with an upper case character. Don't make up your own conventions! – camickr Mar 27 '15 at 02:41

0 Answers0