SFML community forums

Help => Graphics => Topic started by: codinglexernewbie on July 07, 2022, 09:37:21 am

Title: check which glyph is at a position
Post by: codinglexernewbie 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?
Title: Re: check which glyph is at a position
Post by: Arcade on July 07, 2022, 10:01:03 pm
sf::Text provides a few member functions, like getGlobalBounds() (https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Text.php#ad33ed96ce9fbe99610f7f8b6874a16b4) and findCharacterPos() (https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Text.php#a2e252d8dcae3eb61c6c962c0bc674b12), that you can use in combination with some math to get pretty close to what you describe.
Title: Re: check which glyph is at a position
Post by: Hapax 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.