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

Author Topic: How to rotate a rectangle (or another shape) around its center?  (Read 3644 times)

0 Members and 1 Guest are viewing this topic.

smguyk

  • Jr. Member
  • **
  • Posts: 79
    • View Profile
How to rotate a rectangle (or another shape) around its center?
« on: January 13, 2015, 02:46:07 am »
I have a RectangleShape

sf::RectangleShape rect;

and I want it to continuously rotate around its own center.

When I use this code in the loop:

float rotation = rect.getRotation() + 1.0f;
if (rotation >= 360.0f) {
  rotation = 0.0f;
}

rect.setRotation(rotation);

it rotates around its top left corner.

So I tried to alter its origin:

rect.setOrigin(rect.getSize().x * 0.5f, rect.getSize().y * 0.5f);

and now it does rotate around its center, but the center is now where its original top left corner was.

What am I doing wrong, please?

Gambit

  • Sr. Member
  • ****
  • Posts: 283
    • View Profile
Re: How to rotate a rectangle (or another shape) around its center?
« Reply #1 on: January 13, 2015, 02:53:17 am »
After you set the origin you need to offset the shape by half the size.

smguyk

  • Jr. Member
  • **
  • Posts: 79
    • View Profile
Re: How to rotate a rectangle (or another shape) around its center?
« Reply #2 on: January 13, 2015, 07:33:04 am »
Thanks it's working. This is how I'm doing it now:

rect.setPosition(rect.getPosition().x + rect.getOrigin().x, rect.getPosition().y + rect.getOrigin().y);

 

anything