将开关盒用于验证功能(LWJGL 键盘输入)?

Use a switch case for a verification function (LWJGL keyboard input)?

如标题所说。可能吗? 据我所知,没有 getKeyPressed 或任何类似的东西。我想使用 switch case 来组织(和练习)以及速度(或者我被告知)。

基本上,switch case 子句 (?) 只是一个布尔值 return。但是,如果没有 if / else 语句的意大利面碗,我如何根据传递给它的值检查是否按下了一个键?

显然这段代码不起作用,但我正在寻找类似的代码。

public void moveCamera() {
    switch (Keyboard.isKeyDown(!!!CASE CHECKING HERE!!!)) {
        case Keyboard.KEY_W:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_A:
            position.x += MOVE_SPEED;
            break;

        case Keyboard.KEY_S:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_D:
            position.x += MOVE_SPEED;
            break;
    }
}

这是 @KysonTyner.

我喜欢(但没有尝试)的解决方案

You can switch on getEventKey(). This will hit your current cases and then you can wrap the whole switch statement with if (getEventKeyState()) {switch/case}. There is no need to use an event listener. – Kylon Tyner

至于我使用的是什么,我完全放弃了开关的想法,因为我意识到如果输入的方向不止一个,移动速度会成倍增加。

我想支持对角线移动的多个运动方向,所以按下按键时不会 "ghosting"。

我做的是把函数分开,一个测试键盘输入,一个移动相机。键输入不需要任何特殊逻辑,因为它只是将 LWJGL Vector3f 传递给相机移动函数。

然后,在相机移动中,我将该向量归一化并相应地改变了位置。

这是我的相机的简化版class,用于演示。我删除了除翻译之外的所有内容。

package spikespaz.engine.main;

import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector3f;

// Created by spike on 7/3/2017.
public final class Camera {
    private Camera() {}

    private float moveSpeed = 0.2f;
    private Vector3f position = new Vector3f(0, 0, 0);

    public Camera(Vector3f position, Vector3f rotation) {
        this.position = position;
    }

            public void updateKeyInput() {
        Vector3f direction = new Vector3f(0, 0, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
            direction.x = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
            direction.x = -1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
            direction.y = -1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
            direction.y = 1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
            direction.z = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
            direction.z = -1;
        }

        translate(direction);
    }

    private void translate(Vector3f direction) {
        Vector3f normalized = direction.normalise(null);
        Vector3f.add(position, (Vector3f) normalized.scale(moveSpeed), position);
    }

    public float getMoveSpeed() {
        return moveSpeed;
    }

    public void setMoveSpeed(float moveSpeed) {
        this.moveSpeed = moveSpeed;
    }
}

翻译是相对的。完整的class我有另一个设置绝对位置的功能,没有移动速度。

在上面的例子中,平移的输入向量只是一个方向。该功能应根据每帧的移动速度进行协调。