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

Author Topic: Checking the position of the cursor in relation to buttons  (Read 3047 times)

0 Members and 1 Guest are viewing this topic.

Chopa17

  • Newbie
  • *
  • Posts: 2
    • View Profile
Checking the position of the cursor in relation to buttons
« on: September 15, 2018, 05:18:57 pm »
I'm trying to setup a changing texture based upon hovering over a button but having an issue that the hovering isn't matching up with the buttons rectangle, the image below demonstrates the problem for two different sized buttons (which have been cropped out from a maximised window with a titlebar).


This is my relevant piece of code:
void TR_GUI_Button::Draw()
{
        if (!m_bIsVisible) return;

        sf::Sprite xSprite;
        sf::Vector2i xPos = sf::Mouse::getPosition();

        if (!m_xRect.contains(xPos))
        {
                xSprite.setTexture(m_xDefaultTexture);
        }
        else
        {
                xSprite.setTexture(m_xHoverTexture);
        }

        float fScaleX = m_xRect.width / xSprite.getGlobalBounds().width;
        float fScaleY = m_xRect.height / xSprite.getGlobalBounds().height;
        xSprite.setScale(sf::Vector2f(fScaleX, fScaleY));
        xSprite.setPosition(static_cast<float>(m_xRect.left), static_cast<float>(m_xRect.top));

        TR_GameManager::GetGameWindow().draw(xSprite);
}
 

I thought it might be because the window's title bar wasn't being included so I added this code to the draw function:
xPos.y -= ::GetSystemMetrics(SM_CYCAPTION);

This still doesn't match up as it now overcompensates for the larger button.


Any help would be appreciated.

fallahn

  • Hero Member
  • *****
  • Posts: 504
  • Buns.
    • View Profile
    • Trederia
Re: Checking the position of the cursor in relation to buttons
« Reply #1 on: September 15, 2018, 05:35:42 pm »
Try using mapPixelToCoords() to convert your mouse coordinates to world coordinates:

https://www.sfml-dev.org/documentation/2.5.0/classsf_1_1RenderTarget.php#a0103ebebafa43a97e6e6414f8560d5e3

Chopa17

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Checking the position of the cursor in relation to buttons
« Reply #2 on: September 15, 2018, 08:50:44 pm »
Thanks, adding mapPixelToCoords() after subtracting the title bar height does work for fullscreen but not if the window is resized. However, I just found that you can pass the window to the get mouse position function. ie.
sf::Vector2i xPos = sf::Mouse::getPosition( TR_GameManager::GetGameWindow() );
This replaces the manual subtraction of the title bar height and works for resized windows as well.
« Last Edit: September 15, 2018, 08:56:29 pm by Chopa17 »

 

anything