# Rotating problems

## Recommended Posts

Hello, I have created two functions that rotate a mesh. if( ::GetAsyncKeyState(VK_LEFT) & 0x8000f ) { static float y = 0.0f; D3DXMATRIX yRot; D3DXMatrixRotationY(&yRot, y); y += timeDelta; if( y >= 6.28f ) y = 0.0f; D3DXMATRIX World = yRot; Device->SetTransform(D3DTS_WORLD, &World); } if( ::GetAsyncKeyState(VK_RIGHT) & 0x8000f ) { static float y = 0.0f; D3DXMATRIX yRot; D3DXMatrixRotationY(&yRot, y); y -= timeDelta; if( y >= 6.28f ) y = 0.0f; D3DXMATRIX World = yRot; Device->SetTransform(D3DTS_WORLD, &World); } The problem that I'm having is that when I click the left arrow the mesh rotates, however when I click the right arrow button the mesh resets to its original position then rotates. Is there any way I can prevent the reseting of the mesh ? Many Thanks.

##### Share on other sites
Code duplication is bad and is probably what is causing the problem.

If we take the common code out of the if statements we will have this:

static float y = 0.0f;if( ::GetAsyncKeyState(VK_LEFT) & 0x8000f ){    y += timeDelta;    if( y >= 6.28f )    y = 0.0f;}if( ::GetAsyncKeyState(VK_RIGHT) & 0x8000f ){    y -= timeDelta;    if( y >= 6.28f )        y = 0.0f;}D3DXMATRIX yRot;D3DXMatrixRotationY(&yRot, y);D3DXMATRIX World = yRot;Device->SetTransform(D3DTS_WORLD, &World);

First of all, this is much more compact and there is no code duplication. Second of all, this makes it easier to see one problem:

in the first if-block, you are incrementing y and capping it when it exceeds an upper limit. In the second conditional you are decrementing y and capping it when it exceeds an upper limit, but that is incorrect - in this case, you must cap it when it exceeds a lower limit, in this case:
if (y <= 0.0f)    y = 6.28f;

I'm not sure if that fixes the problem but it's one step towards it.

Also, I don't like the two static declarations of y inside the if-blocks. I'm not sure if it contributes to this problem or not though.

##### Share on other sites
Thanks - thats solved the problem.

The only trouble is that its created another one.

Suppose I now wish the up arrow key to rotate along z axis ??

Because I have this code:

D3DXMatrixRotationY(&yRot, y)

When now I'll need this code:

D3DXMatrixRotationZ(&yRot, y)

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628312
• Total Posts
2981998

• 9
• 9
• 13
• 11
• 13