画面上のオブジェクトの描画は OpenGL のかなり基本的な機能ですが、Canvas
オブジェクトや Drawable
オブジェクトなど、他の Android グラフィック フレームワーク クラスでも行うことができます。OpenGL ES は、魅力的なユーザー エクスペリエンスを実現するための 3 次元やその他の独自の方法で、描画されたオブジェクトを移動および変換する追加機能を提供します。
このレッスンでは、OpenGL ES の使用をさらに一歩進め、回転によってシェイプにモーションを追加する方法を学びます。
図形を回転する
OpenGL ES 2.0 による描画オブジェクトの回転は比較的簡単です。レンダラで、別の変換行列(回転行列)を作成し、投影行列およびカメラビュー変換行列と結合します。
Kotlin
private val rotationMatrix = FloatArray(16) override fun onDrawFrame(gl: GL10) { val scratch = FloatArray(16) ... // Create a rotation transformation for the triangle val time = SystemClock.uptimeMillis() % 4000L val angle = 0.090f * time.toInt() Matrix.setRotateM(rotationMatrix, 0, angle, 0f, 0f, -1.0f) // Combine the rotation matrix with the projection and camera view // Note that the vPMatrix factor *must be first* in order // for the matrix multiplication product to be correct. Matrix.multiplyMM(scratch, 0, vPMatrix, 0, rotationMatrix, 0) // Draw triangle mTriangle.draw(scratch) }
Java
private float[] rotationMatrix = new float[16]; @Override public void onDrawFrame(GL10 gl) { float[] scratch = new float[16]; ... // Create a rotation transformation for the triangle long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); Matrix.setRotateM(rotationMatrix, 0, angle, 0, 0, -1.0f); // Combine the rotation matrix with the projection and camera view // Note that the vPMatrix factor *must be first* in order // for the matrix multiplication product to be correct. Matrix.multiplyMM(scratch, 0, vPMatrix, 0, rotationMatrix, 0); // Draw triangle mTriangle.draw(scratch); }
これらの変更を行った後に三角形が回転しない場合は、次のセクションで説明するように、GLSurfaceView.RENDERMODE_WHEN_DIRTY
設定をコメントアウトしていることを確認してください。
連続レンダリングを有効にする
この時点まで、このクラスのサンプルコードに注意深く従った場合、レンダリング モードがダーティの場合にのみ描画される行を設定する行をコメントアウトしてください。そうでなければ、OpenGL はシェイプを 1 増分だけ回転させ、GLSurfaceView
コンテナからの requestRender()
の呼び出しを待機します。
Kotlin
class MyGLSurfaceView(context: Context) : GLSurfaceView(context) { init { ... // Render the view only when there is a change in the drawing data. // To allow the triangle to rotate automatically, this line is commented out: // renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY } }
Java
public class MyGLSurfaceView(Context context) extends GLSurfaceView { ... // Render the view only when there is a change in the drawing data. // To allow the triangle to rotate automatically, this line is commented out: //setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); }
ユーザーの操作なしでオブジェクトを変更する場合を除き、通常はこのフラグをオンにすることをおすすめします。次のレッスンで、この呼び出しが再度適用されるため、このコードのコメントを解除できるようにしてください。