当前位置: 动力学知识库 > 问答 > 编程问答 >

Android OpenGL ES 2.0 Projecting Touch Position

问题描述:

Im new to OpenGL ES 2.0 for Android and I want to make simple application to train my skills. I have a problem with projecting positions. I draw some squares in my apps, and I want to detect which square I hit while touching screen. If I dont use Model-View-Projection Matrix, everything is easy, but when I use MVP Matrix I just dont understand how it works. Here's some code:

in AngelicRenderer class:

@Override

public void onDrawFrame(GL10 unused)

{

GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

// Set the camera position (View matrix)

Matrix.setLookAtM(mViewMatrix, 0, 0f, 0f, 3f, 0f, 0f, 0f, 0f, 1f, 0f);

// Calculate the projection and view transformation

Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);

lock.lock();

try

{

for(Entry> squares : getObjects())

{

for(AngelicSquare square : squares.getValue())

{

square.draw(mMVPMatrix);

}

}

}

finally

{

lock.unlock();

}

}

@Override

public void onSurfaceChanged(GL10 unused, int width, int height)

{

GLES20.glViewport(0, 0, width, height);

float ratio = (float) width / height;

screenWidth = width;

screenHeight = height;

// this projection matrix is applied to object coordinates

// in the onDrawFrame() method

Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1f, 1f, 1f, 10f);

}

in AngelicView class, onTouchEvent:

for(Entry> squares : devilishRenderer.getObjects())

{

for(AngelicSquare square : squares.getValue())

{

float[] coords = square.getPosition();

float[] size = square.getSize();

float[] touchPoint = { e.getX(), e.getY(), 0.0f, 0.0f };

float[] touchPointNew = ViewCoordsToGLCoords(touchPoint);

float[] topLeft = { coords[0], coords[1], 0.0f, 0.0f };

Matrix.multiplyMV(topLeft, 0, devilishRenderer.getMVPMatrix(), 0, topLeft, 0);

float[] bottomRight = { coords[0] + size[0], coords[1] - size[1], 0.0f, 0.0f };

Matrix.multiplyMV(bottomRight, 0, devilishRenderer.getMVPMatrix(), 0, bottomRight, 0);

Matrix.multiplyMV(touchPoint, 0, devilishRenderer.getMVPMatrix(), 0, touchPointNew, 0);

if(touchPoint[0] > topLeft[0] && touchPoint[1] bottomRight[1])

{

hookedSquare = square;

}

}

}

How I can project screens coordinations to OpenGL coordination system with Model-View-Projection Matrix?

分享给朋友:
您可能感兴趣的文章:
随机阅读: