터치 이벤트에 응답

회전하는 삼각형과 같이 미리 설정된 프로그램에 따라 객체를 움직이게 하면 주의를 끄는데 유용하지만, 사용자가 OpenGL ES 그래픽과 상호작용하도록 하려면 어떻게 해야 할까요? OpenGL ES 애플리케이션을 터치에 반응하도록 만들려면 GLSurfaceView 구현을 확장하여 터치 이벤트를 수신 대기하도록 onTouchEvent()를 재정의하는 것이 중요합니다.

이 학습 과정에서는 사용자가 OpenGL ES 객체를 회전할 수 있도록 터치 이벤트를 수신 대기하는 방법을 보여줍니다.

터치 리스너 설정

OpenGL ES 애플리케이션이 터치 이벤트에 응답하도록 하려면 GLSurfaceView 클래스에서 onTouchEvent() 메서드를 구현해야 합니다. 아래의 구현 예에서는 MotionEvent.ACTION_MOVE 이벤트를 수신 대기하고 도형의 회전 각도로 변환하는 방법을 보여줍니다.

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

회전 각도를 계산한 후 이 메서드는 requestRender()를 호출하여 프레임을 렌더링할 때임을 렌더기에 알립니다. 회전이 변경되지 않는 한 프레임을 다시 그릴 필요가 없으므로 이 예에서는 이 접근 방식이 가장 효율적입니다. 그러나 setRenderMode() 메서드를 사용하여 데이터가 변경될 때만 렌더기가 다시 그리도록 요청하지 않는 한 효율성에는 영향을 미치지 않으므로 렌더기에서 다음 줄의 주석 처리를 삭제해야 합니다.

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

회전 각도 노출

위의 코드 예에서는 공개 멤버를 추가하여 렌더기를 통해 회전 각도를 노출해야 합니다. 렌더기 코드는 애플리케이션의 기본 사용자 인터페이스 스레드와 별도의 스레드에서 실행되므로 이 공개 변수를 volatile로 선언해야 합니다. 다음 코드에서는 변수를 선언하고 getter와 setter 쌍을 노출합니다.

Kotlin

class MyGLRenderer4 : GLSurfaceView.Renderer {

    @Volatile
    var angle: Float = 0f
}

자바

public class MyGLRenderer implements GLSurfaceView.Renderer {
    ...

    public volatile float mAngle;

    public float getAngle() {
        return mAngle;
    }

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

회전 적용

터치 입력으로 생성된 회전을 적용하려면 각도를 생성하는 코드를 주석 처리하고 터치 입력이 생성된 각도를 포함하는 변수를 추가합니다.

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

위에 설명된 단계를 완료했으면 프로그램을 실행하고 화면 위로 손가락을 드래그하여 삼각형을 회전합니다.

그림 1. 터치 입력으로 회전되는 삼각형 (원은 터치 위치를 나타냄)