Monday 21 December 2015

Dragging Object in Android OpenGL ES


Continue previous tutorial,

First put this method inside the Stage class:

public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction() & MotionEvent.ACTION_MASK;

return true;
}

The method above is use to detect the pointer finger touch on your phone screen

Next inside the onTouchEvent method create variable float x and y and create variable int pointerIndex

Next go to the renderer and put this function inside:

public void setXY(float x, float y){
xPos = x * w / screenW;
yPos = y * h / screenH;
}

The function above is use to update the position of the texture so later we will call this function to update the position xPos and yPos of the texture

Next inside Stage class create a class variable MyRenderer and name it mRenderer

Next put this code inside the onTouchEvent method:

if(event.getPointerCount()==1){
if (action == MotionEvent.ACTION_POINTER_DOWN){
x = event.getX();
y = event.getY();
} else {
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
}
mRenderer.setXY(x, y);
requestRender();
}

The mRenderer.setXY() function is use to pass the position of the finger pointer x and y and the function requestRender() is use render again the scene after we made some changes in the renderer

Lastly put this code inside the Stage constructor:

mRenderer = new MyRenderer();

setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

The code above is use to detect the changes of the renderer and create the mRenderer variable class, the set render mode must put after the set renderer function

Now you can try to compile it and test the output

Video Tutorial: Click here

1 comment: