Gar*_*ckW 11 c++ opengl rotation quaternions sfml
所以我目前正在尝试创建一个函数,它将采用两个3D点A和B,并为我提供四元数,表示点A要求"看"点B所需的旋转(这样点A的局部Z轴通过B点,如果你愿意).
我最初发现这篇文章,其中最重要的答案似乎为我提供了一个很好的起点.我继续实现以下代码; 而不是假设默认(0,0,-1)方向,正如原始答案所示,我尝试提取表示相机实际方向的单位向量.
void Camera::LookAt(sf::Vector3<float> Target)
{
///Derived from pseudocode found here:
///https://stackoverflow.com/questions/13014973/quaternion-rotate-to
//Get the normalized vector from the camera position to Target
sf::Vector3<float> VectorTo(Target.x - m_Position.x,
Target.y - m_Position.y,
Target.z - m_Position.z);
//Get the length of VectorTo
float VectorLength = sqrt(VectorTo.x*VectorTo.x +
VectorTo.y*VectorTo.y +
VectorTo.z*VectorTo.z);
//Normalize VectorTo
VectorTo.x /= VectorLength;
VectorTo.y /= VectorLength;
VectorTo.z /= VectorLength;
//Straight-ahead vector
sf::Vector3<float> LocalVector = m_Orientation.MultVect(sf::Vector3<float>(0, 0, -1));
//Get the cross product as the axis of rotation
sf::Vector3<float> Axis(VectorTo.y*LocalVector.z - VectorTo.z*LocalVector.y,
VectorTo.z*LocalVector.x - VectorTo.x*LocalVector.z,
VectorTo.x*LocalVector.y - VectorTo.y*LocalVector.x);
//Get the dot product to find the angle
float Angle = acos(VectorTo.x*LocalVector.x +
VectorTo.y*LocalVector.y +
VectorTo.z*LocalVector.z);
//Determine whether or not the angle is positive
//Get the cross product of the axis and the local vector
sf::Vector3<float> ThirdVect(Axis.y*LocalVector.z - Axis.z*LocalVector.y,
Axis.z*LocalVector.x - Axis.x*LocalVector.z,
Axis.x*LocalVector.y - Axis.y*LocalVector.x);
//If the dot product of that and the local vector is negative, so is the angle
if (ThirdVect.x*VectorTo.x + ThirdVect.y*VectorTo.y + ThirdVect.z*VectorTo.z < 0)
{
Angle = -Angle;
}
//Finally, create a quaternion
Quaternion AxisAngle;
AxisAngle.FromAxisAngle(Angle, Axis.x, Axis.y, Axis.z);
//And multiply it into the current orientation
m_Orientation = AxisAngle * m_Orientation;
}
Run Code Online (Sandbox Code Playgroud)
这几乎可行.发生的事情是相机似乎向目标点旋转了一半的距离.如果我再次尝试旋转,它会无限制地执行剩余旋转的一半,这样如果我按住"Look-At-Button",相机的方向会越来越接近直接看目标,但也会不断减慢其旋转,使得它从来没有相当到达那里.
请注意,我不希望诉诸gluLookAt(),我也最终将需要此代码指向对象等在彼此除了相机,和我的对象已经使用四元为自己的方位.例如,我可能想创建一个眼球来跟踪在它前面移动的东西的位置,或者一个更新其方向以寻找其目标的抛射物.
| 归档时间: |
|
| 查看次数: |
5611 次 |
| 最近记录: |