我在OpenGL中绘制了一张地图。我想要的是每当用户触摸屏幕时,我应该得到相对于 OpenGL 地图的坐标,而不仅仅是屏幕坐标。
以下是我尝试过的一段代码,但我没有得到正确的坐标:
// Initialize auxiliary variables.
PointF worldPos = new PointF();
// Auxiliary matrix and vectors
// to deal with ogl.
float[] invertedMatrix, transformMatrix,
normalizedInPoint, outPoint;
invertedMatrix = new float[16];
transformMatrix = new float[16];
normalizedInPoint = new float[4];
outPoint = new float[4];
// Invert y coordinate, as android uses
// top-left, and ogl bottom-left.
int oglTouchY = (int) (scrheigth - touch.Y);
/* Transform the screen point to clip
space in ogl (-1,1) */
normalizedInPoint[0] =
(float) ((touch.X) * 2.0f / scrwidth - 1.0);
normalizedInPoint[1] =
(float) ((oglTouchY) * 2.0f / scrheigth - 1.0);
normalizedInPoint[2] = - 1.0f;
normalizedInPoint[3] = 1.0f;
/* Obtain the transform matrix and
then the inverse. */
Matrix.multiplyMM(
transformMatrix, 0,
mProjMatrix, 0,
mMVPMatrix, 0);
Matrix.invertM(invertedMatrix, 0,
transformMatrix, 0);
/* Apply the inverse to the point
in clip space */
Matrix.multiplyMV(
outPoint, 0,
invertedMatrix, 0,
normalizedInPoint, 0);
if (outPoint[3] == 0.0)
{
// Avoid /0 error.
Log.e("World coords", "ERROR!");
return worldPos;
}