Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Rotating a sprite  (Read 2541 times)

0 Members and 1 Guest are viewing this topic.

rcplusplus

  • Newbie
  • *
  • Posts: 15
    • View Profile
Rotating a sprite
« 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?

Rosme

  • Full Member
  • ***
  • Posts: 169
  • Proud member of the shoe club
    • View Profile
    • Code-Concept
Re: Rotating a sprite
« Reply #1 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!
GitHub
Code Concept
Twitter
Rosme on IRC/Discord

rcplusplus

  • Newbie
  • *
  • Posts: 15
    • View Profile
Re: Rotating a sprite
« Reply #2 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);
}

TheEnigmist

  • Full Member
  • ***
  • Posts: 119
    • View Profile
Re: Rotating a sprite
« Reply #3 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);
}
 

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Rotating a sprite
« Reply #4 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);
}
Laurent Gomila - SFML developer