对象不沿其面向的方向移动,除非旋转为 0 度或 180 度

Object not moving in the direction it's facing unless rotation is 0 or 180 degrees

本文关键字:旋转 度或 移动 方向 对象      更新时间:2023-10-16

正如标题所说,当面向任何非0度或180度的方向时,对象都不会正确移动。这是在三维空间中,但旋转仅在1轴(向上)上,因此对象会左右旋转。以下是一张绘画图,有助于将问题可视化:http://dl.dropbox.com/u/60309894/rotationissue.png按住鼠标右键时,对象会根据鼠标的x增量位置进行旋转。这是代码:

// Check & calculate rotation.
if (mouse->ButtonIsDown(NiInputMouse::NIM_RIGHT))
{
    int iDeltaX = 0, iDeltaY = 0, iDeltaZ = 0;
    mouse->GetPositionDelta(iDeltaX,iDeltaY,iDeltaZ);
    if (iDeltaX != 0)
    {
        NiMatrix3 mMat;
        mMat.MakeRotation(iDeltaX / 100.0f,NiPoint3::UNIT_Z);
        SetRotate(  GetRotate() * mMat  );
    }
}
// Check & calculate movement.
m_vVelocity = NiPoint3::ZERO;
if ( keyboard->KeyIsDown(NiInputKeyboard::KEY_W) == true)
    m_vVelocity.y++;
if ( keyboard->KeyIsDown(NiInputKeyboard::KEY_S) == true)
    m_vVelocity.y-- ;
if ( keyboard->KeyIsDown(NiInputKeyboard::KEY_A) == true)
    m_vVelocity.x--;
if ( keyboard->KeyIsDown(NiInputKeyboard::KEY_D) == true)
    m_vVelocity.x++;
m_vVelocity.Unitize();
// Move the object.
m_spNode->SetTranslate(GetTranslate() + m_vVelocity * GetRotate() * m_fSpeed * dt );

假设X在示例图像中是左和右的,那么看起来只是你的X速度被否定了。如果这是真的,那么交换左右方向,或者否定x速度,应该会解决这个问题:

if ( keyboard->KeyIsDown(NiInputKeyboard::KEY_A) == true)
    m_vVelocity.x++;
if ( keyboard->KeyIsDown(NiInputKeyboard::KEY_D) == true)
    m_vVelocity.x--;

假设z在监视器之外,与原始代码中的右手坐标系相比,这将对应于左手坐标系。

我假设GetRotate()返回一个表示旋转的x和y分量的2D向量(或者3D,只要z不相关,就无关紧要)。如果是这样的话,在设置翻译时可能需要一种不同的方法。这是因为m_vVelocity似乎是对象的局部(即,正y是向前的,但取决于对象的旋转)。

以下可能适用于您:

GetRotate()乘以m_vVelocity.y

接下来,获取GetRotate()返回的向量的法线。将该矢量乘以m_vVelocity.x

将这两个向量相加,得到最终的相对平移向量。所以现在你得到了如下的东西:

// Move the object.
Vector2f forwardVec = GetRotate() * m_vVelocity.y;
Vector2f sideVec    = GetRotate().GetNormal() * m_vVelocity.x;
// Obviously above you need a real method to get the normal of GetRotate,
// I used a "pseudo" method.
m_spNode->SetTranslate(GetTranslate() + forwardVec + sideVec );

编辑:请记住,找到向量法线的方法因2D空间而异(在3D空间中没有为单个向量定义的法线,但在2D空间中有,因此我在上面的示例中使用了2D向量)