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

Author Topic: Rotating a drawing from its center  (Read 169 times)

0 Members and 1 Guest are viewing this topic.

alacrity

  • Newbie
  • *
  • Posts: 1
    • View Profile
Rotating a drawing from its center
« on: January 14, 2024, 04:51:24 pm »
I've tried looking for someone having a similar issue to me, and could not find anything close.
I am trying to create a basic geometry dash copy, and I am having a lot of issues rotating my player square. I am able to rotate it in mid air, just like in geometry dash, but it is rotating with the origin being the top left of the square. This causes a couple of issues for me, but I am only looking to find a solution as to how I can get the origin of rotation to be the center of the square, allowing me to jump and rotate in place. Here is the code and a short gif of the behaviour:
if (!onGround) {
    // Set the origin to the center of the player for rotation
    squarePlayer.setOrigin(0.5f * squarePlayer.getSize());

   float rotationFactor = 180.f * velocityY / sqrt(2.f * jumpHeight * gravity);
    squarePlayer.setRotation(rotationFactor);

    // Draw the player square
    window.draw(squarePlayer);

   // Reset the origin back to the top-left corner after rotation
    squarePlayer.setOrigin(sf::Vector2f(0, 0));
}
else {
    // Draw the player square without rotation
    window.draw(squarePlayer);
}
https://gyazo.com/654f9d56330c5af892cafce09c3eac73

Hapax

  • Hero Member
  • *****
  • Posts: 3351
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Rotating a drawing from its center
« Reply #1 on: January 14, 2024, 10:38:55 pm »
Changing the origin changes the part of the sprite that is at the sprite's position.
This is important to remember.

e.g.
If a sprite is 100x100 and at position (100, 100).
If its origin is at top-left (0, 0), its top left will be at (100, 100) and its centre will be at (150, 150).
It its origin is at centre (50, 50), its centre will be at (100, 100) and its top-left will be at (50, 50).

Basically, set its origin where you want to rotate it and then position that point where you want it.
In your case, set its origin to its centre (and keep it there) and then position its centre when the centre should be.
This means that when its "not rotated", it should have a rotation of 0 and its position should be half of its size added on to where you think its top-left should be.



To be more complete, I shall just add that all transformations are applied around its origin so it rotates around it, scales from/to it and its position matches it.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*