1

我有一个正方形区域,我必须确定鼠标指向的位置。
使用 D3DXIntersectTri 我可以判断鼠标是否指向它,但我无法计算 x、y、z 坐标。

顶点缓冲区的绘图,它使用顶点数组初始化:

vertices[0].position = D3DXVECTOR3(-10, 0,  -10);
vertices[1].position = D3DXVECTOR3(-10, 0,   10);
vertices[2].position = D3DXVECTOR3( 10, 0,  -10);
vertices[3].position = D3DXVECTOR3( 10, 0,  -10);
vertices[4].position = D3DXVECTOR3(-10, 0,   10);
vertices[5].position = D3DXVECTOR3( 10, 0,   10);

到目前为止我有这种方法,这并没有给我正确的坐标(仅适用于区域的一小部分,靠近两个边缘,内部更不准确):

BOOL Area::getcoord( Ray& ray, D3DXVECTOR3& coord)
{
    D3DXVECTOR3 rayOrigin, rayDirection;
    rayDirection = ray.direction;
    rayOrigin = ray.origin;

    float d;

    D3DXMATRIX matInverse;
    D3DXMatrixInverse(&matInverse, NULL, &matWorld);

    // Transform ray origin and direction by inv matrix
    D3DXVECTOR3 rayObjOrigin,rayObjDirection;

    D3DXVec3TransformCoord(&rayOrigin, &rayOrigin, &matInverse);
    D3DXVec3TransformNormal(&rayDirection, &rayDirection, &matInverse);
    D3DXVec3Normalize(&rayDirection,&rayDirection);

    float u, v;
    BOOL isHit1, isHit2;

    D3DXVECTOR3 p1, p2, p3;
    p1 = vertices[3].position;
    p2 = vertices[4].position;
    p3 = vertices[5].position;

    isHit1 = D3DXIntersectTri(&p1, &p2, &p3, &rayOrigin, &rayDirection, &u, &v, &d);
    isHit2 = FALSE;

    if(!isHit1)
    {
        p1 = vertices[0].position;
        p2 = vertices[1].position;
        p3 = vertices[2].position;
        isHit2 = D3DXIntersectTri(&p1, &p2, &p3, &rayOrigin, &rayDirection, &u, &v, &d);
    }

    if(isHit1) 
    {
        coord.x = 1 * ((1-u-v)*p3.x + u*p3.y + v*p3.z);
        coord.y = 0.2f;
        coord.z = -1 * ((1-u-v)*p1.x + u*p1.y + v*p1.z);
        D3DXVec3TransformCoord(&coord, &coord, &matInverse);
    }

    if(isHit2) 
    {
        coord.x = -1 * ((1-u-v)*p3.x + u*p3.y + v*p3.z);
        coord.y = 0.2f;
        coord.z = 1 * ((1-u-v)*p1.x + u*p1.y + v*p1.z);
        D3DXVec3TransformCoord(&coord, &coord, &matWorld);
    }
    return isHit1 || isHit2;
}
4

1 回答 1

1

重心坐标与您使用它们的方式不同。u 和 v 定义源向量的权重。所以如果你想计算命中点,你将不得不计算

coord = u * p1 + v * p2 + (1 - u - v) * p3

或者,您可以使用 d 射线参数:

coord = rayOrigin + d * rDirection

两种方式都应该产生相同的坐标。

于 2012-04-26T07:59:24.783 回答