我正在尝试进行触摸事件并将形状移动到触摸事件移动的任何位置。
public boolean onTouchEvent(MotionEvent e) {
mRenderer.setPosition(e.getX(), e.getY());
return true;
}
问题是我从 MotionEvent 获得的坐标是以像素为单位的屏幕位置,而不是标准化坐标 [-1, 1]。如何将屏幕坐标转换为标准化坐标?提前致谢!
最佳答案
float x = e.getX();
float y = e.getY();
float screenWidth;
float screenHeight;
float sceneX = (x/screenWidth)*2.0f - 1.0f;
float sceneY = (y/screenHeight)*-2.0f + 1.0f; //if bottom is at -1. Otherwise same as X
添加一些更通用的代码:
/*
Source and target represent the 2 coordinate systems you want to translate points between.
For this question the source is some UI view in which top left corner is at (0,0) and bottom right is at (screenWidth, screenHeight)
and destination is an openGL buffer where the parameters are the same as put in "glOrtho", in common cases (-1,1) and (1,-1).
*/
float sourceTopLeftX;
float sourceTopLeftY;
float sourceBottomRightX;
float sourceBottomRightY;
float targetTopLeftX;
float targetTopLeftY;
float targetBottomRightX;
float targetBottomRightY;
//the point you want to translate to another system
float inputX;
float inputY;
//result
float outputX;
float outputY;
outputX = targetTopLeftX + ((inputX - sourceTopLeftX) / (sourceBottomRightX-sourceTopLeftX))*(targetBottomRightX-targetTopLeftX);
outputY = targetTopLeftY + ((inputY - sourceTopLeftY) / (sourceBottomRightY-sourceTopLeftY))*(targetBottomRightY-targetTopLeftY);
使用此方法,您可以平移任何 N 维正交系统之间的任何点(对于 3D,只需为 Z 添加与 X 和 Y 相同的值)。在这个例子中,我使用了 View 的边框坐标,但你可以在场景中使用任意 2 个点,例如,如果使用屏幕中心和右上角,这个方法将完全相同。唯一的限制是
sourceTopLeftX != 每个维度的 sourceBottomRightX
关于Android OpenGL ES : Normalized MotionEvent coordinate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22596275/