Cómo agregar movimiento

Dibujar objetos en la pantalla es una característica bastante básica de OpenGL, pero puedes hacerlo con otras clases de framework de gráficos de Android, incluidos los objetos Canvas y Drawable. OpenGL ES proporciona funciones adicionales para mover y transformar objetos dibujados en tres dimensiones o de otras formas únicas a fin de crear experiencias del usuario atractivas.

En esta lección, se incluye más información sobre OpenGL ES, específicamente, cómo agregar movimiento a una forma con rotación.

Rota una forma

La rotación de un objeto de dibujo con OpenGL ES 2.0 es bastante simple. En tu procesador, crea otra matriz de transformación (una matriz de rotación) y, luego, combínala con las matrices de transformación de proyección y vista de cámara:

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);
    }
    

Si tu triángulo no rota después de realizar estos cambios, asegúrate de haber comentado la configuración GLSurfaceView.RENDERMODE_WHEN_DIRTY, como se describe en la siguiente sección.

Cómo habilitar el procesamiento continuo

Si seguiste con atención el código de ejemplo de esta clase hasta este punto, asegúrate de comentar que la línea que configura el modo de procesamiento solo se dibuja cuando no está sincronizada; de lo contrario, OpenGL solo rota la forma y luego espera una llamada a requestRender() de la GLSurfaceView contenedor:

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);
    }
    

A menos que haya objetos que cambien sin ninguna interacción del usuario, suele ser una buena idea tener esta marca activada. Prepárate para quitar el comentario de este código, ya que, en la siguiente lección, esta llamada vuelve a ser aplicable.