按下多个键

时间:2015-03-26 23:39:51

标签: java awt keylistener

所以我试图找出如何使我的船舶对象旋转并同时向后/向前移动。我做了一些研究,它说我应该使用布尔值使KeyListener同时接受多于1个键。但是当我尝试它时,它不允许我同时做两件事。它取代了我用新的密钥保留的旧密钥。这是我的代码......

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) {
}
}

我知道代码并不完美,但我试图一次完成一件事。

0 个答案:

没有答案