LibGDXは、基本的にすべてのゲームエンジンのように、render()
が呼び出されるたびにシーン全体を再レンダリングします。 render()
は、ゲームのフレームレートで繰り返し呼び出されます(複雑で最適化されていないゲームでは通常60fps)。 render()
メソッドで通常行う最初の描画関連の処理は、すでに完了している画面を消去することです。これはGdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
です。次に、最後のフレーム以降の変更があれば、シーン全体を再描画します。
レンダリングメソッドの外でバッチで何かを描画しようとしています。この場合、あなたはタッチダウンがあるときにそれをやっています。しかし、タッチダウンがある場合にのみこれを行うので、オブジェクトはrender()
への次の呼び出しで表示され消えますので、1/60秒間画面に表示されます。入力プロセッサでこれを行う場合は、レンダリングメソッドが描画する必要があることを示す変数をtrueに設定する必要があります。また、描画する場所を示す変数も必要です。次に、render()
メソッドでは、変数がtrueの場合は要素を描画します。
は第二に、入力プロセッサは必ずしもない(そして通常はない)取得することx
とy
は、OpenGLでx
とy
に対応します。これは、OpenGLには独自の座標系があり、必ずしも画面の座標系と同じサイズにする必要はないからです。画面の左上には(0,0)がY軸になり、画面の幅と高さは画面上の実際のピクセル数に一致します。 OpenGLは画面の中央に(0,0)を持ち、Y軸は上にあり、画面の幅と高さは実際の画面のピクセルに関係なく2です。
しかし、OpenGL座標系は投影行列で修正されています。 LibGDXカメラクラスは、これをより簡単にします。 2D図面では、OrthographicCameraが必要です。 OpenGLワールドの幅とサイズをカメラで設定し、カメラの位置を設定することもできます。次に、カメラの計算された行列をSpriteBatchに渡して、シーンをOpenGL空間に配置します。
シーンの座標に入力座標を取得するには、そのカメラを使用して座標を変換する必要があります。
最後に、LibGDXは入力コマンドを作成した古い入力プロセッサに渡すべきであることを魔法のように知ることはできません。 Gdx.input.setInputProcessor()
への呼び出しで使用する必要があるInputProcessorを教えてください。だからあなたのクラスを修正する
:
SpriteBatch batch;
Texture img;
boolean isTouchDown;
final Vector3 touchPosition = new Vector3();
OrthographicCamera camera;
@Override
public void create() {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
camera = new OrthographicCamera();
Gdx.input.setInputProcessor(new MyInputProcessor()); // Tell LibGDX what to pass input to
}
@Override
void resize (int width, int height) {
// Set the camera's size in relation to screen or window size
// In a real game you would do something more sophisticated or
// use a Viewport class to manage the camera's size to make your
// game resolution-independent.
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update(); // re-calculate the camera's matrices
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined); // pass camera's matrices to batch
batch.begin();
if (isTouchDown) { // Only draw this while the screen is touched.
batch.draw(img, touchPosition.x, touchPosition.y);
}
batch.end();
}
public class MyInputProcessor implements InputProcessor {
public boolean touchDown (int x, int y, int pointer, int button) {
isTouchDown = true;
touchPosition.set(x, y, 0); // Put screen touch coordinates into vector
camera.unproject(touchPosition); // Convert the screen coordinates to world coordinates
return true;
}
public boolean touchUp (int screenX, int screenY, int pointer, int button){
isTouchDown = false;
return true;
}
//... (the rest of the input methods)
}