[英]how to get relative x and y position from mouse click
In my mouse callback, i need to find out where the mosuebutton was clicked relative to the origin(so I need the -1 to 1 value) In the mosue calledback, the GLint is return the value 400 or whatever the x position is. 在我的鼠标回调中,我需要找出相对于原点单击mosuebutton的位置(因此我需要-1到1的值)。在mosue回调中,GLint返回值400或x位置。 How can I get the relative x position or how can I convert the x value? 如何获得x的相对位置或如何转换x值?
void mouseClicked(GLint button,GLint state,GLint x,GLint y)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
//get x of square clicked
if(x<0.0)
{
cout<<"left side of the screen"<<endl;
}
}
}
A mouse click lacks one important information: The depth of where you click. 鼠标单击缺少一个重要信息:单击位置的深度。 All you have is a 2D point on the screen. 您所拥有的只是屏幕上的2D点。 However this maps to a ray into the scene. 但是,这将射线映射到场景中。 The best you can do is determine that ray from the mouse click. 您能做的最好的就是从鼠标单击确定射线。 For this you need to unproject from the viewport to some point on that ray. 为此,您需要从视口取消投影到该射线的某个点。
For this you need to: 为此,您需要:
reverse the viewport mapping, ie map the mouse click coordinates in the viewport back to the range [-1,1] in either coordinate (this gives you NDC), we silently assume the depth will be 1. 反转视口映射,即将视口中的鼠标单击坐标映射回任一坐标中的[-1,1]范围(这将为您提供NDC),我们默默假设深度为1。
un-project, ie multiply the NDC with depth 1 by multiplying with the inverse projection matrix 非投影,即通过与逆投影矩阵相乘将NDC与深度1相乘
un-modelview, ie multiply the unprojected point by multiplying with the inverse modelview matrix. 非模型视图,即通过与反模型视图矩阵相乘来相乘非投影点。
If either projection or modelview matrix are singular, ie are not invertible this will not work. 如果投影矩阵或模型视图矩阵是奇异的,即不可逆,则将无法使用。
The GLU library offers this, including matrix inversion in the function gluUnproject . GLU库提供了此功能,包括在函数gluUnproject中进行矩阵求逆。
The result is a point on the ray. 其结果是在光线的点。 The ray itself is given by the ray equation r(\\tau) = r_0 * tau, where r_0 is that one point you got. 射线本身由射线方程r(\\ tau)= r_0 * tau给出,其中r_0是您得到的一点。
a quick answer to your question would be like so: 对您的问题的快速解答如下:
void mouseClicked(GLint button,GLint state,GLint x,GLint y)
{
// Convert x & y
GLfloat fX = ((x/g_cxScreen) - 0.5) * 2;
GLfloat fY = ((y/g_cyScreen) - 0.5) * 2;
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
//get x of square clicked
if(x<0.0)
{
cout<<"left side of the screen"<<endl;
}
}
}
This assumes g_cxScreen and g_cyScreen are the screen width and height respectively. 假设g_cxScreen和g_cyScreen分别是屏幕的宽度和高度。 This will normalise your mouse coords. 这将使您的鼠标坐标正常化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.