LWJGL Basics 2 (Input)

LWJGL Basics 2 (Input)

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

public class InputExample {
  public void start() {
    try {
      Display.setDisplayMode(new DisplayMode(800, 600));
      Display.create();
    } catch (LWJGLException e) {
      e.printStackTrace();
      System.exit(0);
    }

    while (!Display.isCloseRequested()) {
      pollInput();
      Display.update();
    }

    Display.destroy();
  }

  public void pollInput() {
    if (Mouse.isButtonDown(0)) {
      int x = Mouse.getX();
      int y = Mouse.getY();
      System.out.println("MOUSE DOWN @ X: " + x + " Y: " + y);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
      System.out.println("SPACE KEY IS DOWN");
    }

    while (Keyboard.next()) {
      if (Keyboard.getEventKeyState()) {
        if (Keyboard.getEventKey() == Keyboard.KEY_A) {
          System.out.println("A Key Pressed");
        }
        if (Keyboard.getEventKey() == Keyboard.KEY_S) {
          System.out.println("S Key Pressed");
        }
        if (Keyboard.getEventKey() == Keyboard.KEY_D) {
          System.out.println("D Key Pressed");
        }
      } else {
        if (Keyboard.getEventKey() == Keyboard.KEY_A) {
          System.out.println("A Key Released");
        }
        if (Keyboard.getEventKey() == Keyboard.KEY_S) {
          System.out.println("S Key Released");
        }
        if (Keyboard.getEventKey() == Keyboard.KEY_D) {
          System.out.println("D Key Released");
        }
      }
    }
  }

  public static void main(String[] argv) { 
    InputExample inputExample = new InputExample();
    inputExample.start();
  }
}

このサンプルで扱われているのはマウスとキーボードからの入力についてで、それぞれMouse, Keyboardクラスを利用しています。

マウス

マウスの位置については、Mouse.getX(), Mouse.getY() でウィンドウ内でのXY座標を取得できます。座標原点は左下となっています。

また、クリックされたボタンの判定は Mouse.isButtonDown() で判定します。このメソッドは引数に0-2の整数を受け取り、クリックされた場合はtrueを返します。引数となる整数値は0から2までそれぞれ、左クリック、右クリック、中クリックに対応しています。

キーボード

キーボードは Keyboard.isKeyDown(Keyboard.KEY_X) のようにして判定します。引数をKeyboard.KEY_Xとするとxキー、Keyboard.KEY_Aとするとaキーというように、入力されたキーを特定できます。

イベントバッファー

入力イベントを全て処理するような場合には、Keyboard.next()Mouse.next() メソッドを使用します。

入力の状態を取得するには Keyboard.getEventKeyState(), Mouse.getEventButtonState() が利用でき、押された状態であれば true を取得できます。

また、どのキーの入力イベントか判定するには Keyboard.getEventKey(), Mouse.getEventButton() を使用します。返り値は Keyboard.KEY_AKeyboard.KEY_X などの入力値となっています。

コメント

このブログの人気の投稿

[Java] 母音か子音か

git-svnでFILE was not found in commit HASH

駄文