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

Author Topic: Trying to use a sf::RectangleShape's Origin for the position of some text.  (Read 3437 times)

0 Members and 1 Guest are viewing this topic.

Wake

  • Newbie
  • *
  • Posts: 11
    • View Profile
    • Email
Hi,

Please see the attached images below.

Image #1 shows how I set the origin of the sf::RectangleShape.
I want it to be in the dead center. So half of x & y.

Image #2 shows how I'm trying to set the position of the text to the origin of the sf::RectangleShape.

Image #3 shows that the text is nowhere near the text box. What happened?

I saw you can set an origin for the sf::Text. Should I make it half the font size for x & y? Does that even matter?

Best,
Wake

Wake

  • Newbie
  • *
  • Posts: 11
    • View Profile
    • Email
I got it to work in a hacky kind of way using the sf::RectangleShape's position, then offsetting it via trial and error.

I would like to learn a clean way to play text directly in the center of shapes and sprites though :)


Hapax

  • Hero Member
  • *****
  • Posts: 3351
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
I don't know why you're using the rectangle's origin (in the rectangle's local co-ordinate system) for the text's origin (in the text's local co-ordinate system).

If you want the origin to be the centre for both, set that origin based on each object size (and position offset for text). Then, once the origins are correctly set, you can set both of their positions to the same position and they would both have their centres in the same place (they would be aligned to their centres).

For texts, use the local bounds to calculate where the local origin should be. Remember that not just the size (width and height) but the offset (left and top) should be taken into account.

To set the origin of a text to its centre:
// "text" is the text object
const sf::FloatRect textLocalBounds{ text.getLocalBounds() };
text.setOrigin({ (localBounds.left + localBounds.width) / 2.f, (localBounds.top + localBounds.height) / 2.f });
Important note: this code should be executed whenever (and after) the text string is changed and it's based on the actual text string.
(or simply executed every loop - before it is drawn)
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

 

anything