### Author Topic: check which glyph is at a position  (Read 540 times)

0 Members and 1 Guest are viewing this topic.

#### codinglexernewbie

• Newbie
• Posts: 4
##### check which glyph is at a position
« on: July 07, 2022, 09:37:21 am »
say my mouse clicks on '√' in the SF::text "a√a" i want to know which glyph is at the position the mouse clicked and the glyph's bounding box's location,how would i do that?

• Full Member
• Posts: 230
##### Re: check which glyph is at a position
« Reply #1 on: July 07, 2022, 10:01:03 pm »
sf::Text provides a few member functions, like getGlobalBounds() and findCharacterPos(), that you can use in combination with some math to get pretty close to what you describe.

#### Hapax

• Hero Member
• Posts: 3100
• My number of posts is shown in hexadecimal.
##### Re: check which glyph is at a position
« Reply #2 on: July 16, 2022, 09:16:46 pm »
Since I find little problems fun, I decided to get an answer to this. Normally, people would not just provide the answer rather than just point you in the right direction to find it for yourself (which is clearly the best thing to do) but I got bored and intrigued so threw this together:

char characterUnderMouse = '\n';
const sf::Vector2f mousePosition{ window.mapPixelToCoords(sf::Mouse::getPosition(window)) };
if (text.getGlobalBounds().contains(mousePosition))
{
for (std::size_t i{ 0u }; i < text.getString().getSize(); ++i)
{
if (text.findCharacterPos(i).x > mousePosition.x)
break;
characterUnderMouse = text.getString()[i];
}
}

If you really see how this would be used, here's an complete example program that shows it in action (don't look if you don't need to!):
(click to show/hide)

It's very important to note that this only covers single line text and non-transformed text.
« Last Edit: July 16, 2022, 09:19:08 pm by Hapax »
Selba Ward - SFML drawables
Kairos - Timing Library
Rectangular Boundary Collision - Rectangular SAT Collision