当我按住一个键时,我试图让一个简单的实体/玩家移动,但它只会在我按下它时移动,而不是按住它。我以为是我的 while 循环中的 Keyboard.next() ,但这不起作用。
import static org.lwjgl.opengl.GL11.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.lwjgl.input.Mouse;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.*;
import org.lwjgl.*;
public class Main {
int x = 50;
int y = 50;
int dx = 1;
int dy = 1;
long lastFrame;
double delta;
public Main() {
try {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.setTitle("Input Demo");
Display.create();
} catch(LWJGLException e) {
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GL11.glOrtho(0, 800, 0, 600, 1, -1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
while(!Display.isCloseRequested()) {
//Render
glClear(GL_COLOR_BUFFER_BIT);
drawPlayer();
movePlayer();
Display.update();
Display.sync(60); //60 fps
System.out.println("LastFrame:" + lastFrame);
System.out.println("Delta:" + delta);
}
Display.destroy();
}
public void movePlayer() {
while(Keyboard.next()) {
double delta = getDelta();
if(Keyboard.isKeyDown(Keyboard.KEY_W)) {
y += 3 * dy;
} else if(Keyboard.getEventKey() == Keyboard.KEY_S && Keyboard.getEventKeyState()) {
y -= 3 * dy;
} else if(Keyboard.getEventKey() == Keyboard.KEY_A && Keyboard.getEventKeyState()) {
x -= 3 * dx;
} else if(Keyboard.getEventKey() == Keyboard.KEY_D && Keyboard.getEventKeyState()) {
x += 3 * dx;
}
}
}
public void drawPlayer() {
glColor3f(3, 0, 0);
glPushMatrix();
glTranslatef(x, y, 0);
glBegin(GL_QUADS);
glVertex2f(x - 25, y - 25);
glVertex2f(x + 25, y - 25);
glVertex2f(x + 25, y + 25);
glVertex2f(x - 25, y + 25);
glEnd();
glPopMatrix();
}
public long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
public double getDelta() {
long currentTime = getTime();
double delta = (double)(currentTime - lastFrame);
lastFrame = getTime();
return delta;
}
public void update(int dx, int dy) {
x += dx;
y += dy;
}
public static void main(String[] argv) {
new Main();
}
}