Strange SFML behavior

本小妞迷上赌 提交于 2019-12-24 08:20:42

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/25149152/strange-sfml-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!