Search code examples
c++rotationdirectxspritedirectx-9

C++ DirectX9 incorrect sprite rotation


I have a problem with sprite rotation. Sprite is missing from screen after rotation, why? I just want rotate sprite on 270 degress (4.712 radian).

D3DXMATRIX mat;

m_sprite->Begin(D3DXSPRITE_ALPHABLEND);
m_sprite->GetTransform(&mat);
D3DXMatrixTransformation2D(&mat, NULL, NULL, NULL, &D3DXVECTOR2(m_width / 2, m_height / 2), rotation, &D3DXVECTOR2(m_posX, m_posY));
m_sprite->SetTransform(&mat);
m_sprite->Draw(m_texture, NULL, NULL, &m_pos, -1);
m_sprite->End();

Solution

  • The following code get current transform matrix.

    m_sprite->GetTransform(&mat);
    

    The following code calculate the new transform matrix, which will overwrite matrix mat since you use the same variable.

    D3DXMatrixTransformation2D(&mat, NULL, NULL, NULL, &D3DXVECTOR2(m_width / 2, m_height / 2), rotation, &D3DXVECTOR2(m_posX, m_posY));
    

    The following code restore the old transform matrix which will not work, the old transform was lost, you only apply the new transform.

    m_sprite->SetTransform(&mat);
    

    You'd better use a different matrix variable when calculate the new transform matrix and then multiply it with the old transform matrix to get the final matrix.

    D3DXMATRIX newmat;
    D3DXMatrixTransformation2D(&newmat, NULL, NULL, NULL, &D3DXVECTOR2(m_width / 2, m_height / 2), rotation, &D3DXVECTOR2(m_posX, m_posY));
    mat *= newmat;
    m_sprite->SetTransform(&mat);