1

我在OpenGL中有一个摄像头,它可以在 X 和 Z 轴上移动。

您可以使用左右箭头按钮旋转相机,并使用WASD 按钮向前、向后、向左和向右移动。这是移动的方法。

public void move(float amount, float dir) {
    z += amount * Math.sin((Math.toRadians(ry + 90 * dir)));
    x += amount * Math.cos((Math.toRadians(ry + 90 * dir)));
}

amount ”是速度,“ dir ”是“0”或“1”,因此它将“90”设置为“0”或将其保留为“90”​​。“ z ”是z轴上的位置。如“ x ”和“ y ”。“ rz ” 是在 z 轴上的旋转。如“ rx ”和“ ry ”。

有了这些,我就不能在 Y 轴上移动,也就是 UP 和 DOWN。我设法添加了旋转代码以使相机向上向下,但我无法使相机转到您正在看地方。这是旋转方法:

public void rotate(float amount, float way) {
    if (way == ROTATE_RIGHT)
    ry += amount;
    else if (way == ROTATE_LEFT)
    ry -= amount;
    if (way == ROTATE_UP && rx >= -90)
    rx -= amount;
    else if (way == ROTATE_DOWN && rx <= 90)
    rx += amount;
}

这就是我调用 move() 方法的方式。

if (Keyboard.isKeyDown(Keyboard.KEY_W))
    cam.move(0.01f, Camera.MOVE_STRAIGHT);

if (Keyboard.isKeyDown(Keyboard.KEY_S))
    cam.move(-0.01f, Camera.MOVE_STRAIGHT);

if (Keyboard.isKeyDown(Keyboard.KEY_A))
    cam.move(0.01f, Camera.MOVE_STRAFE);

if (Keyboard.isKeyDown(Keyboard.KEY_D))
    cam.move(-0.01f, Camera.MOVE_STRAFE);

Camera.MOVE_STRAIGHT = 1Camera.MOVE_STRAFE = 0并且cam 是一个 Camera 对象。

4

1 回答 1

1

编辑 1:忘记改变 X/Z 运动。这应该可以解决这些问题。

编辑 2:更改amountwalkAmountstrafeAmount用于两种类型的水平移动。y现在也用walkAmount.

编辑 3:添加move()

public void move(float amount, float dir) {
    /* If you are moving straight ahead, or in reverse, modify the Y value for ascent/descent
     * Since you do not change your elevation if you are strafing, dir will be 0. sin(0) = 0, and the elevation will not change (regardless of whether rx is 0).
     * When you are moving forward or in reverse, dir will be 1, so the rotation about the x axis will be used, and the elevation will change (unless rx is 0).
     */
    y += amount * Math.sin(Math.toRadians(rx) * dir);

    /* If you are moving straight ahead, or in reverse, scale the delta X/Z (what comes after the +=) so that you don't move as far.
     * For example, if you are aimed straight up, and you move straight ahead (W/S), Math.cos(Math.toRadians(rx) * dir) will evaluate to 0, since you only want to move in the Y direction.
     * If you are aimed perfectly straight ahead (rotation about the x axis is 0), and you move straight ahead (A/D), Math.cos(Math.toRadians(rx) * dir) will evalute to 1, and your X/Z
     * movement would use the entire amount, since you are no longer moving in the Y direction.
     * If you are strafing (A/D), dir will be 0, and Math.cos(Math.toRadians(rx) * dir) will evalute to 1 (cos(0) == 1)). You will ONLY move in the X/Z directions when strafing.
     */
    z += amount * Math.cos(Math.toRadians(rx) * dir) * Math.sin((Math.toRadians(ry + 90 * dir)));
    x += amount * Math.cos(Math.toRadians(rx) * dir) * Math.cos((Math.toRadians(ry + 90 * dir)));
}

如果这对您有帮助或您有任何问题,请告诉我。

于 2013-08-05T09:32:37.020 回答