0

I'm fairly new to OpenGl programing and know that you use translate, for moving an shape. But do I also use this to move an shape to where the user has touched the screen? or would I use the onTouchEvent to accomplish this? and how.

I have looked at various sources regarding this including: How to move a OpenGL square with the finger? https://developer.android.com/training/graphics/opengl/touch.html

However I still do not understand how this can be done.

Any help is appreciated.

Community
  • 1
  • 1
DarkEnergy
  • 21
  • 6

1 Answers1

0

There are 2 things you need to do. First get the location of the touch with onTouchEvent and then use some method to move the object such as translate.

When you get the event you will get the location in view which needs to be translated to your openGL coordinate system. To figure your coordinate system you will need to take a look into what projection and or view matrix you are using (if any). The default coordinate system is left:-1, right:1, top:1, bottom:-1 but if you use ortho then you will need to use those coordinates. For more complicated systems you should look into some other answers answers on how to translate the location in your view to the openGL coordinate. So for the ortho (or no matrix) procedure the result is:

float viewX, viewY; // got from event
float surfaceViewWidth, surfaceViewHeight; // Size of your view
float left, right, top, bottom; // From ortho or default (-1, 1, 1, -1)

float glX = left + (viewX/surfaceViewWidth)*(right-left);
float glY = top + (viewY/surfaceViewHeight)*(bottom-top);

Ok so now that you have your location in the scene you will need to move the object. The most common way is to use translate on the model matrix before drawing the object whenever you redraw so for that you need to save the glX and glY in your renderer so that you can use the values in the draw method to translate the object. A better way is to have a class that contains all the data for your model so you would say model.x = glX and model.y = glY but that is your choice. Some other choices are to invalidate the vertex buffer and recreate your vertices when the event is received but I do not suggest you to use this procedure. Another way is to keep the model matrix and translate that matrix but that is more appropriate for dragging...

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
  • For moving the shape it will be dragging. So how would I translate the model matrix as I'm currently doing Matrix.translateM(mTriangle.mModelMatrix,0,0,0,0); and putting the model matrix as the x and y coordinates does not work. – DarkEnergy Dec 23 '16 at 22:02
  • Well you need to translate it for the difference of the two touch locations. For instance if previous touch was at (10,10) and next one is at (12,14) you will translate it by (2,4) which is (12-10, 14-10). – Matic Oblak Jan 03 '17 at 08:10