Hello again cplusplus.com peeps.
I'm making a 2D platformer with DirectX. I have a sprite for my player's arm that I want to rotate to always be pointing at the cursor. I managed to get it working using some basic (and probably ghetto-rigged) trig, but only when the arm was in a static position, by itself.
Using getCursorPos(), I moused over the arm for the coordinates (vec2 m_Arm.pos) of the pivot point and used those with the current cursor position (vec2 m_Cursor) to calculate the rotation. So I had an arbitrarily placed arm that would rotate to point at the cursor. So far so good.
Next, I changed the pivot point (m_Arm.pos) to the position of my player (vec2 m_oPlayer.pos) so the rotating arm would actually move around with the player's body.
The problem is, I use the player's vector for world coordinates like so:
1 2 3 4 5
|
D3DXMatrixScaling(&scaleMat, 1.0f, 1.0f, 1.0f);
D3DXMatrixTranslation(&transMat, m_oPlayer.pos.x, m_oPlayer.pos.y, 0.0f);
D3DXMatrixMultiply(&worldMat, &scaleMat, &transMat);
m_pD3DSprite->SetTransform(&worldMat);
|
...and here's how I calculate the rotation of the arm:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
//Cursor updates
GetCursorPos(&m_Cursor);
ScreenToClient(m_hWnd, &m_Cursor);
//Dynamic arm updates
m_Arm.worldPos.x = m_oPlayer.pos.x-340;
m_Arm.worldPos.y = m_oPlayer.pos.y-58;
//m_Arm.cursorPos.x = 135;
//m_Arm.cursorPos.y = 450;
m_Arm.cursorPos.x = m_oPlayer.pos.x * 0.281f;
m_Arm.cursorPos.y = m_oPlayer.pos.y * 0.9f;
m_Arm.deltaCursor.x = m_Cursor.x <= m_Arm.cursorPos.x ? (m_Cursor.x - m_Arm.cursorPos.x) : (m_Arm.cursorPos.x - m_Cursor.x);
m_Arm.deltaCursor.y = m_Cursor.y <= m_Arm.cursorPos.y ? (m_Cursor.y - m_Arm.cursorPos.y) : (m_Arm.cursorPos.y - m_Cursor.y);
if(m_Cursor.y <= m_Arm.cursorPos.y)
{
//Quadrant 1
if(m_Cursor.x >= m_Arm.cursorPos.x)
{
m_Arm.rot = atan((double)m_Arm.deltaCursor.x/m_Arm.deltaCursor.y);
m_Arm.rot += D3DXToRadian(180);
if(m_Cursor.y == m_Arm.cursorPos.y)
m_Arm.rot = D3DXToRadian(-90);
}
//Quadrant 2
else
{
m_Arm.rot = atan((double)m_Arm.deltaCursor.y/m_Arm.deltaCursor.x);
m_Arm.rot += D3DXToRadian(90);
}
}
else
{
//Quadrant 3
if(m_Cursor.x < m_Arm.cursorPos.x)
m_Arm.rot = atan((double)m_Arm.deltaCursor.x/m_Arm.deltaCursor.y);
//Quadrant 4
else
{
m_Arm.rot = atan((double)m_Arm.deltaCursor.y/m_Arm.deltaCursor.x);
m_Arm.rot -= D3DXToRadian(90);
}
}
|
Lines 9 and 10 are using the coordinates I got from mousing over the arm. Lines 11 and 12 are my attempt at converting the world coordinates of the arm to the moused-over coordinates, but those multipliers only work in the arm's initial position.
So I need to either convert the mouse coordinates to world coordinates, or the other way around. Despite a solid 2.5 hours of googling and reading other people's seemingly relevant problems, I'm still stuck.