Search code examples
javaandroidopengl-esandroid-cameratouch-event

openGL in java: moving camera with TouchEvent


I need to create a movement/changing position of the camera with the x,y axes by touching screen. I've read many of the previous questions, but nowhere noticed something that will solve my problem.

how can i use this code ? :

class ESSurfaceView extends GLSurfaceView {

private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float mPreviousX;
private float mPreviousY;

@Override
public boolean onTouchEvent(MotionEvent e) {

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

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

            float dx = x - mPreviousX;
            float dy = y - mPreviousY;

            if (y > getHeight() / 2) {
                dx = dx * -1 ;
            }

            if (x < getWidth() / 2) {
                dy = dy * -1 ;
            }

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

    mPreviousX = x;
    mPreviousY = y;
    return true;
}

public ESSurfaceView(Context context)
{
    super(context);

    setEGLContextClientVersion(2);
    GLRenderer renderer = new GLRenderer();
    setRenderer(renderer);

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

Solution

  • Offical Android Training has an example (mostly identically to yours) for that: https://developer.android.com/training/graphics/opengl/touch.html It also offers complete source.

    By the way - you never move the camera in openGL - you move the world. For further understanding please read: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ This should give you a better understanding on how things work...