How do you rotate a sprite around its center by caclulating a new x and y position?

Posted by Sam152 on Stack Overflow See other posts from Stack Overflow or by Sam152
Published on 2009-10-17T09:02:40Z Indexed on 2010/03/23 23:43 UTC
Read the original article Hit count: 334

Filed under:
|

I'm using Dark GDK and C++ to create a simple 2d game. I'm rotating an object but it rotates from the top left corner of the sprite.

I have the following variables available:

  • PlayerX
  • PlayerY
  • PlayerWidth
  • PlayerHeight
  • RotateAngle (360 > x > 0)

Is there an algorithm that will modify the pivot point of the sprite, preferable to the center?

Here is a small code sample:

void Player::Move( void )
{

    if ( checkLeft() )
    {
    	PlayerX -= PlayerSpeed;
    	if ( PlayerX < 0 )
    		PlayerX = 0;
    }

    if ( checkRight() )
    {
    	PlayerX += PlayerSpeed ;
    	if ( PlayerX > 800 - PlayerWidth )
    		PlayerX = 800 - PlayerWidth;
    }

    if ( checkUp())
    {
    	PlayerY -= PlayerSpeed;
    	if ( PlayerY < 0 )
    		PlayerY = 0;
    }

    if ( checkDown())
    {
    	PlayerY += PlayerSpeed;
    	if ( PlayerY > 600 -  PlayerHeight)
    		PlayerY = 600 - PlayerHeight;
    }

    RotateAngle += 5;
    if(RotateAngle > 360)
    	RotateAngle -=360;

    dbRotateSprite(Handle,RotateAngle);
    dbSprite ( 1 , PlayerX , PlayerY , Handle );
}

Edit

I'm considering opening up some reputation for this question, I have yet to be provided with an answer that works for me. If someone can provide an actual code sample that does the job, I'd be very happy.

The problem with Blindy's answer is that no matter how much I simply translate it back or forth, the spirte still rotates around the top left hand corner and moving it somewhere rotating around the top left corner, then moving it back to the same position accomplishes nothing. Here is what I believe to be going on:

alt text

Just so there is no confusion I have created a an image of what is going on. The left shows what is actually happening and the right shows what I need to happen.

alt text

© Stack Overflow or respective owner

Related posts about c++

Related posts about game-development