简体   繁体   English

创建一个从点到鼠标的x,y的矢量,OpenGL,C ++

[英]Create a vector from a point to the x,y of the mouse, OpenGL, C++

I am trying to write a OpenGL application where an object is fired from a point( In this case 0,0,0 ) and flies to the x,y position of the mouse. 我正在尝试编写一个OpenGL应用程序,其中从一个点(在这种情况下为0,0,0)发射了一个对象,并飞到了鼠标的x,y位置。 This is the system I am currently using: Create an object at the point 0,0,0 Get the x,y position of the mouse. 这是我当前正在使用的系统:在0,0,0点创建一个对象获取鼠标的x,y位置。 Convert the mouse to 3d co-ordinates. 将鼠标转换为3d坐标。 Get a line between the start point and (mouse-X,m mouse-Y, far plane ) where the far plane is set to 4,294,967,295. 在起点和(mouse-X,m mouse-Y,far plane)之间获得一条线,其中将远平面设置为4,294,967,295。 Use the parametric line equation to move the object along this line. 使用参数线方程式可沿该线移动对象。

The problem is that the x,y on the far plane does not seem to correspond to the x,y mouse position so the object flies on the wrong line. 问题在于,远端平面上的x,y似乎与x,y鼠标的位置不对应,因此对象在错误的线上飞行。 I am pretty sure that the line/para,etric equation part is working ok, but the conversion between 2d and 3-d space may not. 我很确定线/对等式方程部分工作正常,但是2d和3d空间之间的转换可能不行。 Here is what I have tried: 这是我尝试过的:

First convert to window co-ordinates: 首先转换为窗口坐标:

POINT *mouse = new POINT();
mouse->x = mousePosition3D.x;
mouse->y = mousePosition3D.y;
ScreenToClient( windowHandle, mouse ); 

Then to 3-d co-ordinates 然后到3维坐标

GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
OBJ_TriCo returnMe;

//All matrices in use need to be retrived 
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );
//Set the co-ords to lookup, based on the mouse position passed to this
winX = (float)x;
winY = (float)viewport[3] - (float)y;
//Set the z to 0.99, for some reason the object will fly totally incorrectly otherwise
winZ = 0.999; //Get a point on the bettween FAR and NEAR-Clipping planes
//Convert the co-ords 
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
//Return there values
returnMe.x = posX;
returnMe.y = posY;
returnMe.z = posZ;
return returnMe;

I am wondering has any body do anything similar to this or what maths i may need to do to get the objects to fly along the correct line. 我想知道是否有任何人体可以做与此类似的事情,或者我可能需要做些什么数学运算才能使物体沿着正确的方向飞行。

You can calculate world space ray direction from screen-space coordinates (normalized to range [-1, 1]) like this: 您可以像这样从屏幕空间坐标(归一化为[-1,1]范围)来计算世界空间射线方向:

vec4f r = projection_to_view_matrix * vec4f(screen_x, screen_y, 0, 1);
vec3f rdir = transpose(world_to_view_rotation_matrix) * vec3f(r.x, r.y, r.z);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM