モーションの追加

画面上でのオブジェクトの描画は 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 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);
    }
    

ユーザーによる操作なしでオブジェクトを変更しない限り、通常はこのフラグをオンにすることをおすすめします。次のレッスンでこの呼び出しをもう一度行うため、このコードのコメントを外せるようにしておきます。