【问题标题】:Calculating the Angle Between a 3D Object and a Point计算 3D 对象和点之间的角度
【发布时间】:2013-10-04 08:26:11
【问题描述】:

我在 DirectX11 中有一个 3D 对象,它有一个位置矢量和它所面对方向的旋转角度(它只围绕 Y 轴旋转)。

D3DXVECTOR3 m_position;
float       m_angle;

如果我想旋转对象以面对某物,那么我需要使用两个归一化向量上的点积来找到它所面对的方向和它需要面对的方向之间的角度。

我遇到的问题是我如何仅通过它的位置和角度找到对象当前面对的方向。我目前拥有的是:

D3DXVECTOR3 normDirection, normTarget;
D3DXVec3Normalize( &normDirection, ????);
D3DXVec3Normalize( &normTarget, &(m_position-target));

// I store the values in degrees because I prefer it
float angleToRotate = D3DXToDegree( acos( D3DXVec3Dot( &normDirection, &normTarget)));

有谁知道我如何从我拥有的值中获取它所面临的当前方向的向量,还是我需要重新编写它以便跟踪对象的方向向量?

编辑:将“cos”更改为“acos”。

解决方案(在 user2802841 的协助下):

// assuming these are member variables
D3DXVECTOR3 m_position;
D3DXVECTOR3 m_rotation;
D3DXVECTOR3 m_direction;

// and these are local variables
D3DXVECTOR3 target;  // passed in as a parameter
D3DXVECTOR3 targetNorm;
D3DXVECTOR3 upVector;
float angleToRotate;

// find the amount to rotate by
D3DXVec3Normalize( &targetNorm, &(target-m_position));
angleToRotate = D3DXToDegree( acos( D3DXVec3Dot( &targetNorm, &m_direction)));

// calculate the up vector between the two vectors
D3DXVec3Cross( &upVector, &m_direction, &targetNorm);

// switch the angle to negative if the up vector is going down
if( upVector.y < 0)
    angleToRotate *= -1;

// add the rotation to the object's overall rotation
m_rotation.y += angleToRotate;

【问题讨论】:

    标签: c++ vector 3d rotation dot-product


    【解决方案1】:

    如果您将方向存储为角度,那么当角度为 0 时,您必须假设某种默认方向,如果您假设 x+ 方向为默认方向,则将该默认方向表示为矢量(如 (1.0, 0.0, 0.0) ),然后按您的角度旋转该向量(directly with sin/cos 或使用由one of the D3DXMatrixRotation* 函数创建的旋转矩阵),生成的向量将是您当前的方向。

    编辑:

    在回答您的评论时,您可以确定旋转方向like this。在您的情况下,这意味着(未经测试):

    D3DXVECTOR3 cross;
    D3DXVec3Cross(&cross, &normDirection, &normTarget);
    float dot;
    D3DXVec3Dot(&dot, &cross, &normal);
    if (dot < 0) {
        // angle is negative
    } else {
        // angle is positive
    }
    

    normal 很可能是一个 (0, 1, 0) 向量(因为您说您的对象围绕 Y 轴旋转)。

    【讨论】:

    • 如何通过旋转矩阵来旋转矢量?从我所看到的你不能做D3DXVECTOR3 = D3DXVECTOR3 * D3DXMATRIX。是的,我现在意识到,至少在我的程序中,0 度 == (0, 0, 1)。
    • @Edward 试试D3DXVec3TransformCoord
    • 谢谢,这正是我所需要的。然而,另一个问题由此而来。如果我将位置设置为 (5, 3, 0) 并将目标位置设置为 (7.5, 3, 2.5) 它正确地计算出角度为 45 度,但是当我将目标设置为 (7.5) 时角度仍然是 45 度, 3, -2.5)。有没有确定旋转方向的方法?
    • @Edward 我用可以帮助你的信息编辑了答案。
    • 确实如此。我已经对其进行了测试,并且确实叉积正是我所需要的。 (更新了我的问题以包含完整的解决方案)。
    【解决方案2】:

    如果,如您所说,0 度 == (0,0,1) 您可以使用:

    normDirection = ( sin( 角度 ), 0, cos( 角度 ) )

    因为旋转总是围绕 y 轴。

    您必须根据您的系统(左撇子或右撇子)更改 sin(angle) 的符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多