0

我在 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;
4

2 回答 2

1

如果将方向存储为角度,则必须在角度为 0 时假设某种默认方向,将该默认方向表示为矢量(如 (1.0, 0.0, 0.0),如果假设 x+ 方向为默认值),则按您的角度旋转该向量(直接使用 sin/cos或使用由D3DXMatrixRotation* 函数之一创建的旋转矩阵),生成的向量将是您当前的方向。

编辑:

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

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 轴旋转)。

于 2013-09-27T23:47:08.840 回答
1

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

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

因为旋转总是围绕 y 轴。

您将不得不根据您的系统(左手或右手)更改 sin(angle) 的符号。

于 2013-09-28T09:49:39.167 回答