Newer
Older
AlgebraicDataflowArchitectureModel / GameEngine / src / main / java / gameEngine / input / KeyInput.java
package gameEngine.input;

import static org.lwjgl.glfw.GLFW.*;

public class KeyInput {
    private static KeyInput instance;
    private boolean keyPressed[] = new boolean[GLFW_KEY_LAST + 1]; // 押されている状態を保持
    private boolean keyDown[] = new boolean[GLFW_KEY_LAST + 1];    // 押された瞬間を検知
    private boolean keyUp[] = new boolean[GLFW_KEY_LAST + 1];      // 離された瞬間を検知

    private KeyInput() {
    }

    public static KeyInput get() {
        if (KeyInput.instance == null) {
            KeyInput.instance = new KeyInput();
        }
        return KeyInput.instance;
    }

    public static void keyCallback(long window, int key, int scancode, int action, int mods) {
        if (key <= GLFW_KEY_LAST && key >= 0) {
            KeyInput input = get();
            if (action == GLFW_PRESS) {
                if (!input.keyPressed[key]) {
                    input.keyDown[key] = true;  // 押された瞬間
                }
                input.keyPressed[key] = true;
            } else if (action == GLFW_RELEASE) {
                input.keyPressed[key] = false;
                input.keyUp[key] = true;        // 離された瞬間
            }
        }
    }

    protected static boolean isKeyDown(int keyCode) {
        if (keyCode <= GLFW_KEY_LAST && keyCode >= 0) {
            boolean result = get().keyDown[keyCode];
            get().keyDown[keyCode] = false; // 一度だけ検知するため、クリア
            return result;
        }
        return false;
    }

    protected static boolean isKeyPressed(int keyCode) {
        if (keyCode <= GLFW_KEY_LAST && keyCode >= 0) {
            return get().keyPressed[keyCode];
        }
        return false;
    }

    protected static boolean isKeyUp(int keyCode) {
        if (keyCode <= GLFW_KEY_LAST && keyCode >= 0) {
            boolean result = get().keyUp[keyCode];
            get().keyUp[keyCode] = false; // 一度だけ検知するため、クリア
            return result;
        }
        return false;
    }
}