Adicionar movimento

Desenhar objetos na tela é um recurso bem básico do OpenGL, mas você pode fazer isso com outras classes do framework gráfico do Android, incluindo objetos Canvas e Drawable. O OpenGL ES oferece outros recursos para mover e transformar objetos desenhados em três dimensões ou de outras maneiras exclusivas para criar experiências do usuário atrativas.

Nesta lição, você vai dar outro passo no uso do OpenGL ES aprendendo a adicionar movimento a uma forma com rotação.

Girar uma forma

Girar um objeto de desenho com o OpenGL ES 2.0 é relativamente simples. No renderizador, crie outra matriz de transformação (uma matriz de rotação) e combine-a com suas matrizes de transformação de projeção e visualização de câmera:

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

Se o triângulo não girar depois dessas mudanças, confira se você comentou a configuração GLSurfaceView.RENDERMODE_WHEN_DIRTY, conforme descrito na próxima seção.

Ativar renderização contínua

Se você acompanhou atentamente o código de exemplo desta classe até este ponto, comente a linha que define o modo de renderização para desenhar apenas quando estiver suja. Caso contrário, o OpenGL gira a forma apenas um incremento e espera uma chamada para requestRender() do contêiner GLSurfaceView:

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

A menos que você tenha objetos mudando sem interação do usuário, normalmente é uma boa ideia ativar essa flag. Prepare-se para remover a marca de comentário desse código, porque a próxima lição torna essa chamada aplicável novamente.