SFML community forums

Help => Graphics => Topic started by: rcplusplus on June 01, 2012, 02:19:57 am

Title: Rotating a sprite
Post by: rcplusplus on June 01, 2012, 02:19:57 am
I have this sprite I want to rotate, but when I call SetRotation() on it, it behaves weird, like the hinge is on the top left corner. I'm aware that I can use SetCenter() to place the hinge in the center of the sprite, but I like positioning elements using the top left corner. I wrote a wrapper class for sf::Sprite and wrote the setRotation() method like this:

void CSprite::setRotation(float degrees)
{
   float oldXCenter = drawable.GetCenter().x;
   float oldYCenter = drawable.GetCenter().y;
   drawable.SetRotation(degrees);
   drawable.SetPosition(oldXCenter, oldYCenter);
}

But it still doesn't do what I want... Does anyone have a solution?
Title: Re: Rotating a sprite
Post by: Rosme on June 01, 2012, 05:17:56 am
Save the center position(oldPos), setcenter for the hinge to be in the center, rotate, set center to oldPos ?
Not sure though!
Title: Re: Rotating a sprite
Post by: rcplusplus on June 01, 2012, 06:43:35 am
I've tried that before, but it doesn't work. Specifically I tried it like this before:

void CSprite::setRotation(float degrees)
{
   drawable.SetCenter(get_width()/2, get_height()/2);
   drawable.SetRotation(degrees);
   drawable.SetCenter(0, 0);
}
Title: Re: Rotating a sprite
Post by: TheEnigmist on June 01, 2012, 07:28:49 am
void CSprite::setRotation(float degrees)
{
   drawable.SetOrigin(get_width()/2, get_height()/2);
   drawable.SetRotation(degrees);
   drawable.SetOrigin(0, 0);
}
 
Title: Re: Rotating a sprite
Post by: Laurent on June 01, 2012, 07:59:38 am
SetRotation/SetCenter/etc. are not applied immediately, they are combined at draw time, and always in the same order. So calling SetCenter/SetRotation/SetCenter has no effect -- only the very last SetCenter is taken in account.

The solution is simply to add the center to the position so that it's still like the position origin is the top-left corner (so you have to overload setPosition, not setRotation)
void CSprite::setPosition(float x, float y)
{
   drawable.SetPosition(x + drawable.GetCenter().x, y + drawable.GetCenter().y);
}