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

Author Topic: [SOLVED] Handle mouse click on non-transparent part of sprite.  (Read 1818 times)

0 Members and 1 Guest are viewing this topic.

tariel36

  • Newbie
  • *
  • Posts: 5
    • View Profile
[SOLVED] Handle mouse click on non-transparent part of sprite.
« on: October 05, 2016, 05:12:41 pm »
Hello everyone!

I am trying to handle clicks on non-transparent part of sf::Sprite. I've created texture in .png format which contains transparent background. I handle clicks with following code:

zones = ...;
sf::Sprite someSprite = ...;

MouseState mState = InputManager::I().GetMouseState();

for (int i = 0, size = zones.size(); i < size; ++i)
{
   
   if (mState.LeftButtonClicked && someSprite.getGlobalBounds().contains(mState.PositionX, mState.PositionY))
   {
      // ... some code
   }

   // ... more code
}

Mouse state updates and clicks are handled properly, however clicks on the transparent part of the sf::Sprite are detected as inside sprite (which is correct I suppose, since getGlobalBounds returns (bounding?) rectangle).

I need to handle clicks only on visible part of the sprite.
Does SFML support such thing? If so, how to achieve that?
Do I have to handle this myself? If so, how to achieve that? (Not asking for actual code, but tips/algorithms/etc).

See attachment for visualisation and example texture file.

« Last Edit: October 05, 2016, 06:46:37 pm by tariel36 »

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
AW: Handle mouse click on non-transparent part of sprite.
« Reply #1 on: October 05, 2016, 05:32:41 pm »
You have to handle it yourself.

One way is to store a copy of the sf::Image of your texture (or rather you load the image into an sf::Image and then construct the texture from it) and match the mouse position to the position on the image and check the underlying pixel alpha value.

Main question being whether it's really worth doing a transparent check or whether a shape "approximation" check is better. For example if it's a circle there are math formulas that are easier to use and may perform better, while not requiring an additional sf::Image instance.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

tariel36

  • Newbie
  • *
  • Posts: 5
    • View Profile
Re: Handle mouse click on non-transparent part of sprite.
« Reply #2 on: October 05, 2016, 06:31:12 pm »
I see, thank you for your reply. For the provided example texture it's not worth at all, however it was just an example to simplify the question. The actual shapes are much more complex (mostly concave).

 

anything