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

Author Topic: Sprite Vertical axis rotation  (Read 2510 times)

0 Members and 1 Guest are viewing this topic.

ypcman

  • Newbie
  • *
  • Posts: 3
    • View Profile
Sprite Vertical axis rotation
« on: November 24, 2023, 03:17:14 pm »
Hi.
I'm trying to rotate a sprite by its vertical axis. For example, rotate a sprite with a person walking to the right become a person walking to the left. I only found sfSprite_rotate() and sfSprite_setRotation() which rotate a sprite upon a point ...
Is there a simple function to do this ?
« Last Edit: November 24, 2023, 03:25:01 pm by ypcman »

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Sprite Vertical axis rotation
« Reply #1 on: November 24, 2023, 04:27:12 pm »
Rotation around horizontal or vertical axis would be 3D and SFML is 2D.

However, you can "flip" a texture so that it faces in the other direction.
The simplest way to do this is to simply "scale" it with a negative value:

sprite.setScale({ -1.f, 1.f });

would flip it horizontally (similar to rotating 180 degrees around the vertical axis).

Note that if you are already scaling the sprite, you should use the negative equivalent of its x value. e.g:
sprite.setScale({ 4.f, 4.f }); // your normal scaling
sprite.setScale({ -4.f, 4.f }); // flip x but keep your normal scaling

You can also apply a simple flip but it would need to be applied when it flips (not constantly):
sprite.scale({ -1.f, 1.f });
simply flips it horizontally. If you do it again, it will flip back. The other option (setScale) has more control.

Note that scaling is around its origin and its origin is - by default - at the top-left corner. This means that flipping (scaling by a negative value) will make it appear the other side of its position. To flip in place, you can either:
offset its position by its size (just x position by its width if just flipping x):
sf::Vector2f intendedSpriteTopLeftPosition{ 100.f, 100.f };
sprite.setPosition(intendedSpriteTopLeftPosition + sf::Vector2f{ static_cast<float>(sprite.getTextureRect().width), 0.f, });
or set it origin to its centre:
sprite.setOrigin(sf::Vector2f(sprite.getTextureRect().getSize() / 2));

If you change its origin, its position will also change. You will need to account for this. [A sprite's position tell the sprite where you want its origin to be]
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

ypcman

  • Newbie
  • *
  • Posts: 3
    • View Profile
Re: Sprite Vertical axis rotation
« Reply #2 on: November 24, 2023, 05:02:56 pm »
it's exactly what I needed !!
Thanks a lot Hapax