SFML community forums

Help => Graphics => Topic started by: sfmlnoob123 on April 24, 2020, 04:58:02 pm

Title: Object doesn't rotate from the cente even though the origin is set correctly
Post by: sfmlnoob123 on April 24, 2020, 04:58:02 pm
Hey,
I want to make the object rotation so it's relative to the mouse position.

In constructor I set the origin to the centre of the object and set its position:
Quote
Player::Player() {
   setOrigin(width / 2, height / 2);
   pos.x = 600.f;
   pos.y = 300.f;
}

then I calculate the angle:
Quote
float Player::getAngle(sf::RenderWindow& window) {
   x = sf::Mouse::getPosition(window).x - (pos.x + width / 2);
   y = sf::Mouse::getPosition(window).y - (pos.y + height / 2);
   angle = std::atan2(y, x) * 180 / M_PI;
   printf("%f\n", angle);
   return angle;
}

and draw it. However the origin seems to be very off because it rotates around a different point.
What am I missing?
Title: Re: Object doesn't rotate from the cente even though the origin is set correctly
Post by: Laurent on April 24, 2020, 06:35:36 pm
What's the local size (getLocalBounds()) of Player? What the value of width / 2 and height / 2?
Title: Re: Object doesn't rotate from the cente even though the origin is set correctly
Post by: sfmlnoob123 on April 24, 2020, 06:41:42 pm
What's the local size (getLocalBounds()) of Player? What the value of width / 2 and height / 2?

Player isn't a sf::Sprite so can't call getLocalBounds. That is how I set its position:
Quote
m_vertices[0] = sf::Vector2f(pos.x, pos.y);
m_vertices[1] = sf::Vector2f(pos.x + width, pos.y);
m_vertices[2] = sf::Vector2f(pos.x + width, pos.y + height);
m_vertices[3] = sf::Vector2f(pos.x, pos.y + height);

Width and height are both 128.
Title: Re: Object doesn't rotate from the cente even though the origin is set correctly
Post by: Laurent on April 24, 2020, 08:01:09 pm
Vertices should be defined in local coordinates (0 instead of pox.s and pos.y), and position should be applied as a translation in the object's transform (setPosition if it's a sf::Transformable).
Title: Re: Object doesn't rotate from the cente even though the origin is set correctly
Post by: sfmlnoob123 on April 24, 2020, 08:12:59 pm
Thank you! It worked.