c++ - 计算 3D 对象和点之间的角度

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

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

D3DXVECTOR3 m_position;
float       m_angle;

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

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

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)));

有谁知道我如何从我拥有的值中获取当前方向的 vector ,或者我是否需要重写它以便跟踪对象的方向 vector ?

编辑:将“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;

最佳答案

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

编辑:

在回答您的评论时,您可以确定旋转方向 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) vector (因为您说过您的对象绕 Y 轴旋转)。

关于c++ - 计算 3D 对象和点之间的角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19060934/

相关文章:

python - 将 2D 图像转换为 3D

c++ - URL 的最短路径算法

c++ - 当 shared_ptr 的实例仍在范围内时共享指针的对象被删除

c++ - 省略数据类型(例如 "unsigned"而不是 "unsigned int")

java - 如何在 Java 中过滤数组?

css - 使用 CSS 翻转 3D 卡片

c++ - c++中变量的奇怪行为

pointers - 如何使用指针算法获取向量中元素的索引?

c++ - 在 C++ 中初始化 vector 的 vector

c++ - OpenGL 网格错误位置