Responder a eventos de toque

Fazer com que objetos se movam de acordo com um programa predefinido, como o triângulo giratório, é útil para chamar atenção, mas e se você quiser que os usuários interajam com seus gráficos do OpenGL ES? A chave para tornar o aplicativo OpenGL ES interativo por toque é expandir a implementação de GLSurfaceView para substituir o onTouchEvent() para detectar eventos de toque.

Esta lição mostra como ouvir eventos de toque para permitir que os usuários girem um objeto OpenGL ES.

Configurar um listener de toque

Para fazer com que seu aplicativo OpenGL ES responda a eventos de toque, implemente o método onTouchEvent() na sua classe GLSurfaceView. O exemplo de implementação abaixo mostra como detectar eventos MotionEvent.ACTION_MOVE e convertê-los em um ângulo de rotação de uma forma.

Kotlin

private const val TOUCH_SCALE_FACTOR: Float = 180.0f / 320f
...
private var previousX: Float = 0f
private var previousY: Float = 0f

override fun onTouchEvent(e: MotionEvent): Boolean {
    // MotionEvent reports input details from the touch screen
    // and other input controls. In this case, you are only
    // interested in events where the touch position changed.

    val x: Float = e.x
    val y: Float = e.y

    when (e.action) {
        MotionEvent.ACTION_MOVE -> {

            var dx: Float = x - previousX
            var dy: Float = y - previousY

            // reverse direction of rotation above the mid-line
            if (y > height / 2) {
                dx *= -1
            }

            // reverse direction of rotation to left of the mid-line
            if (x < width / 2) {
                dy *= -1
            }

            renderer.angle += (dx + dy) * TOUCH_SCALE_FACTOR
            requestRender()
        }
    }

    previousX = x
    previousY = y
    return true
}

Java

private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float previousX;
private float previousY;

@Override
public boolean onTouchEvent(MotionEvent e) {
    // MotionEvent reports input details from the touch screen
    // and other input controls. In this case, you are only
    // interested in events where the touch position changed.

    float x = e.getX();
    float y = e.getY();

    switch (e.getAction()) {
        case MotionEvent.ACTION_MOVE:

            float dx = x - previousX;
            float dy = y - previousY;

            // reverse direction of rotation above the mid-line
            if (y > getHeight() / 2) {
              dx = dx * -1 ;
            }

            // reverse direction of rotation to left of the mid-line
            if (x < getWidth() / 2) {
              dy = dy * -1 ;
            }

            renderer.setAngle(
                    renderer.getAngle() +
                    ((dx + dy) * TOUCH_SCALE_FACTOR));
            requestRender();
    }

    previousX = x;
    previousY = y;
    return true;
}

Observe que, depois de calcular o ângulo de rotação, esse método chama requestRender() para informar ao renderizador que é hora de renderizar o frame. Essa abordagem é a mais eficiente neste exemplo, porque o frame não precisa ser redesenhado, a menos que haja uma mudança na rotação. No entanto, ele não tem nenhum impacto na eficiência, a menos que você também solicite que o renderizador só redesenhe quando os dados mudarem usando o método setRenderMode(). Portanto, certifique-se de que essa linha não seja comentada no renderizador:

Kotlin

class MyGlSurfaceView(context: Context) : GLSurfaceView(context) {

    init {
        // Render the view only when there is a change in the drawing data
        renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
    }
}

Java

public MyGLSurfaceView(Context context) {
    ...
    // Render the view only when there is a change in the drawing data
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}

Expor o ângulo de rotação

O código de exemplo acima exige que você exponha o ângulo de rotação pelo renderizador adicionando um membro público. Como o código do renderizador está sendo executado em uma linha de execução separada da linha de execução principal da interface do usuário do seu aplicativo, você precisa declarar essa variável pública como volatile. Este é o código para declarar a variável e expor o par de getter e setter:

Kotlin

class MyGLRenderer4 : GLSurfaceView.Renderer {

    @Volatile
    var angle: Float = 0f
}

Java

public class MyGLRenderer implements GLSurfaceView.Renderer {
    ...

    public volatile float mAngle;

    public float getAngle() {
        return mAngle;
    }

    public void setAngle(float angle) {
        mAngle = angle;
    }
}

Aplicar rotação

Para aplicar a rotação gerada pela entrada de toque, comente o código que gera um ângulo e adicione uma variável que contenha o ângulo gerado pela entrada de toque:

Kotlin

override fun onDrawFrame(gl: GL10) {
    ...
    val scratch = FloatArray(16)

    // Create a rotation for the triangle
    // long time = SystemClock.uptimeMillis() % 4000L;
    // float angle = 0.090f * ((int) time);
    Matrix.setRotateM(rotationMatrix, 0, angle, 0f, 0f, -1.0f)

    // Combine the rotation matrix with the projection and camera view
    // Note that the mvpMatrix factor *must be first* in order
    // for the matrix multiplication product to be correct.
    Matrix.multiplyMM(scratch, 0, mvpMatrix, 0, rotationMatrix, 0)

    // Draw triangle
    triangle.draw(scratch)
}

Java

public void onDrawFrame(GL10 gl) {
    ...
    float[] scratch = new float[16];

    // Create a rotation for the triangle
    // long time = SystemClock.uptimeMillis() % 4000L;
    // float angle = 0.090f * ((int) time);
    Matrix.setRotateM(rotationMatrix, 0, mAngle, 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);
}

Quando concluir as etapas descritas acima, execute o programa e arraste o dedo sobre a tela para girar o triângulo:

Figura 1. Triângulo sendo girado com entrada por toque (o círculo mostra o local do toque).