简体   繁体   中英

Strange SFML behavior

I'm currently trying to write a button class. It takes 2 textures, m_texture and m_onHover , and its caption, which should be automatically centered. The function update() takes care of selecting the correct texture.

class button : public sf::Drawable
{
private:
    const sf::Texture *m_texture;
    const sf::Texture *m_onHover;
    sf::Sprite m_sprite;

public:
    button(); 

    sf::Text m_caption; // public to allow easy formating, see centerCaption()

    bool mouseIsOver() const;
    void update();

    void setPosition(sf::Vector2f position);
    void setPosition(float x, float y);

    void centerCaption();

    // Access functions
    void setTexture(const sf::Texture &texture) { m_texture = &texture;     m_sprite.setTexture(*m_texture); }
    void setonHoverTexture(const sf::Texture &texture) { m_onHover = &texture; }
    void setCaption(sf::String text)    { m_caption.setString(text);        centerCaption(); }
    void setFontSize(unsigned int size) { m_caption.setCharacterSize(size); centerCaption(); }
    void setFont(sf::Font& font) { m_caption.setFont(font); }

private:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
};

bool button::mouseIsOver() const
{
    if (m_sprite.getGlobalBounds().contains(sf::Vector2f(sf::Mouse::getPosition())))    // creating a float vector for contains() because getPosition gives int vector
    {
        return true;
    }
    else
    {
        return false;
    }
}

Everything seems to be working, but the mouse position at which mouseIsOver() returns true seems to be moved 40 pixels above the sprite. The values in the rect from getGlobalBounds() seem to be correct when printed in the console.

Unluckily I dont have enough reputation to post a screenshot.

The cursor position should be translated to the proper coordinate system. Basically you need to use sf::RenderTarget::mapPixelToCoords (available in sf::Renderwindow by inheritance). For more details, have a look at the documentation and §Coordinates conversions of the official tutorial.

Also, you might want to consider making your button class inherit from sf::Transformable so that you don't have to manage the position/rotation/scale/... yourself. Have a look at Creating a SFML-like entity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM