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.