我正在使用LWJGL制作3D游戏,我想添加一个支持鼠标的第一人称照相机。我目前有一个,但它不顺畅,根本不能很好地工作。我真的很想让窗户也集中,所以鼠标已经啮合而不是悬停在窗户上方。我该如何实现呢?
这是我目前的相机实现:
public class Camera {
private Vector3f position = new Vector3f(0,5,0);
private float pitch = 10;
private float yaw;
private float roll;
private float speed = 0.2f;
public Camera() {
}
public void move() {
yaw = - (Display.getWidth() - Mouse.getX() / 4);
pitch = (Display.getHeight() / 1000) - Mouse.getY();
if (pitch >= 90) {
pitch = 90;
}
else if (pitch <= -90) {
pitch = -90;
}
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
position.z += -(float)Math.cos(Math.toRadians(yaw)) * speed;
position.x += (float)Math.sin(Math.toRadians(yaw)) * speed;
}
else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
position.z -= -(float)Math.cos(Math.toRadians(yaw)) * speed;
position.x -= (float)Math.sin(Math.toRadians(yaw)) * speed;
}
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
position.z += (float)Math.sin(Math.toRadians(yaw)) * speed;
position.x += (float)Math.cos(Math.toRadians(yaw)) * speed;
}
else if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
position.z -= (float)Math.sin(Math.toRadians(yaw)) * speed;
position.x -= (float)Math.cos(Math.toRadians(yaw)) * speed;
}
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
position.y -= speed;
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
position.y += speed;
}
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
System.exit(0);
}
}
public Vector3f getPosition() {
return position;
}
public float getPitch() {
return pitch;
}
public float getYaw() {
return yaw;
}
public float getRoll() {
return roll;
}
}
答案 0 :(得分:0)
在计算偏航和俯仰时你正在进行整数除法,这很糟糕,因为结果也是一个整数。要改变这一点,你只需要将一个值设为浮点数:
yaw = - (Display.getWidth() - Mouse.getX() / 4f);
pitch = (Display.getHeight() / 1000f) - Mouse.getY();
现在结果会更精确。
虽然我建议使用此代码来计算你的音高和偏航:
float rotationSpeed = 1.0; //You probably need to change this factor
yaw -= Mouse.getDX() / rotationSpeed;
pitch += Mouse.getDY() / rotationSpeed;
getDX / Y()返回自上次调用getDX / Y()以来x / y轴上的移动。
如果你想专注于窗口,只需调用Mouse.setGrabbed(true)。