如何通过鼠标点击获取相对x和y位置
在我的鼠标回调中,我需要找出相对于原点单击 mosuebutton 的位置(因此我需要 -1 到 1 值)在 mosue 回调中,GLint 返回值 400 或任何 x 位置。如何获取相对 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;
}
}
}
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. How can I get the relative x position or how can I convert the x value?
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
鼠标单击缺少一项重要信息:单击位置的深度。您所拥有的只是屏幕上的一个 2D 点。然而,这会映射到场景中的光线。您能做的最好的事情就是通过鼠标单击来确定该射线。为此,您需要从视口取消投影到该射线上的某个点。
为此,您需要:
反转视口映射,即将视口中的鼠标单击坐标映射回任一坐标中的 [-1,1] 范围(这为您提供 NDC),我们默默地假设深度将为1.
un-project,即将深度为1的NDC乘以逆投影矩阵
un-modelview,即通过乘以逆模型视图矩阵来乘以未投影点。
如果投影或模型视图矩阵是奇异的,即不可逆,则这将不起作用。
GLU 库提供了此功能,包括函数 gluUnproject 中的矩阵求逆。
结果是射线上的一个点。射线本身由射线方程 r(\tau) = r_0 * tau 给出,其中 r_0 是您得到的一点。
A mouse click lacks one important information: The depth of where you click. All you have is a 2D point on the screen. 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, i.e. 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.
un-project, i.e. multiply the NDC with depth 1 by multiplying with the inverse projection matrix
un-modelview, i.e. multiply the unprojected point by multiplying with the inverse modelview matrix.
If either projection or modelview matrix are singular, i.e. are not invertible this will not work.
The GLU library offers this, including matrix inversion in the function 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.
对您的问题的快速回答如下:
假设 g_cxScreen 和 g_cyScreen 分别是屏幕宽度和高度。这将使您的鼠标坐标正常化。
a quick answer to your question would be like so:
This assumes g_cxScreen and g_cyScreen are the screen width and height respectively. This will normalise your mouse coords.