OpenGL翻译与键输入

时间:2012-12-24 13:08:57

标签: java opengl lwjgl

我决定随机启动一个小型OpenGL 2D游戏,问题是,我的键盘输入无效。没有错误或任何东西,但是,我创建的小方块拒绝移动。这是我的玩家类:

public class Player {

 public int x = 0;
 public int y = 0;
 static int walkSpeed = 2;

 private InputHandler input;

 public Player() {
    render();
    update();

 }

 public void update(){
    input = new InputHandler();

    if (input.up) y--;
    if (input.down) y++;
    if (input.left) x--;
    if (input.right) x++;
 }

 public void render() {
    glTranslatef(x, y, 0);

    glBegin(GL_QUADS);
    glVertex2i(300, 300);// upper left
    glVertex2i(350, 300);// upper right
    glVertex2i(350, 350);// bottom right
    glVertex2i(300, 350);// bottom left
    glEnd();
 }
}

我的输入处理程序:

public class InputHandler implements KeyListener{

private boolean[] keys = new boolean[120];  
public boolean up, down, left, right, exit;

public void update(){
    up = keys[KeyEvent.VK_W];
    down = keys[KeyEvent.VK_S];
    left = keys[KeyEvent.VK_A];
    right = keys[KeyEvent.VK_D];
    exit = keys[KeyEvent.VK_ESCAPE];
}

public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

public void keyTyped(KeyEvent e) {

}}

我在主类中调用keylistener,如下所示:

public class Main extends Canvas{
long lastFrame;
long fps;
long lastFps;
private InputHandler key;

public Main(){
    try {
        Display.setDisplayMode(new DisplayMode(800, 600));
        Display.setTitle("OpenGL Platformer");
        Display.create();
    }catch (LWJGLException e){
        e.printStackTrace();
    }

    getDelta();

    lastFps = getTime();
    key = new InputHandler();
    addKeyListener(key);

具体而言,此代码添加了侦听器:

        addKeyListener(key);

我该怎么办?

1 个答案:

答案 0 :(得分:0)

处理输入事件后,您必须发出重绘事件,以便实际绘制内容。