将鼠标坐标转换为3d坐标

时间:2013-05-28 19:04:55

标签: directx-11

我有以下问题: 我有我的鼠标坐标,我有一个模型(数据点),我想要我的鼠标坐标的3d坐标和我的lookAt这个坐标的矢量,这样我就可以用对象进行光线投射,这样我就可以看到3d数据点的值。所以我想用鼠标点击然后我想看到我点击的数据点的坐标。

我在教程中有以下内容,但它不起作用。光线原点和光线方向不正确(我在光线方向上从光线原点绘制I线,光线原点不对: 谁能帮我?这是代码:

    // Move the mouse cursor coordinates into the -1 to +1 range.
pointX = ((2.0f * (float)mouseX) / (float) screen_width) - 1.0f;
pointY = (((2.0f * (float)mouseY) / (float) screen_height) - 1.0f) * -1.0f;


m_D3D->GetProjectionMatrix(projectionMatrix);

pointX = pointX / projectionMatrix._11;
pointY = pointY / projectionMatrix._22;

// Get the inverse of the view matrix.
m_Camera->GetViewMatrix(viewMatrix);
D3DXMatrixInverse(&inverseViewMatrix, NULL, &viewMatrix);

// Calculate the direction of the picking ray in view space.
direction.x = (pointX * inverseViewMatrix._11) + (pointY * inverseViewMatrix._21)+ 
    inverseViewMatrix._31;
direction.y = (pointX * inverseViewMatrix._12) + (pointY * inverseViewMatrix._22) 
    + inverseViewMatrix._32;
direction.z = (pointX * inverseViewMatrix._13) + (pointY * inverseViewMatrix._23) 
    + inverseViewMatrix._33;

// Get the origin of the picking ray which is the position of the camera.
origin = m_Camera->GetPosition();

// Get the world matrix and translate to the location of the sphere.
m_Impact->GetWorldMatrix(worldMatrix);
//D3DXMatrixTranslation(&translateMatrix, -5.0f, 1.0f, 5.0f);
//D3DXMatrixMultiply(&worldMatrix, &worldMatrix, &translateMatrix); 

// Now get the inverse of the translated world matrix.
D3DXMatrixInverse(&inverseWorldMatrix, NULL, &worldMatrix);


D3DXVec3TransformCoord(&rayOrigin, &origin, &inverseWorldMatrix);
D3DXVec3TransformNormal(&rayDirection, &direction, &inverseWorldMatrix);

// Normalize the ray direction.
D3DXVec3Normalize(&rayDirection, &rayDirection);

//collision_object->setTransform(col_matrix);
    collision_model->setTransform(col_matrix);
    float collision_point[3];
    //bool collision_result = collision_object ->rayCollision(rayOrigin, 
             rayDirection, true);
    bool collision_result = collision_model ->rayCollision(rayOrigin, 
            rayDirection, true);

             if(collision_result == true)
    {
        intersect = true;
        //collision_object->getCollisionPoint(collision_point, true);
        collision_model->getCollisionPoint(collision_point, false);
        *coordX = collision_point[0];
        *coordY = collision_point[1];
        *coordZ = collision_point[2];



    }

1 个答案:

答案 0 :(得分:1)

从鼠标构建光线的一种简单方法如下(伪代码)

获取鼠标坐标-1 - > 1范围(你已经做过)

创建视图投影矩阵(视图*投影) 反转它。

创建2个鼠标向量:

near = Vector3(mousex,mousey,0);
far = Vector3(mousex,mousey,1);

rayorigin = transformcoord(near, inverseviewprojection);
rayend = transformcoord(far, inverseviewprojection);
raydir = normalize(rayend-rayorigin);