Getting clicked position using SFML

*爱你&永不变心* 提交于 2019-12-13 05:27:31

问题


I'm currently learning SFML on my own, and trying to figure out how to print out the position of the clicked area at bposX and bposY in the pollevent section. Thi s is my codes:


sf::RectangleShape smallRectangle (float width = 1.0f, float height = 1.0f, 
                                sf::Vector2f position = sf::Vector2f(1.0f,1.0f),
                                const sf::Color& myFillColor = sf::Color(0,51, 51)
                                )
{
  sf::RectangleShape sboard;
  sf::Vector2f myRectangleSize(width, height);
  sboard.setSize(myRectangleSize);
  sboard.setPosition(position);
  sboard.setFillColor(myFillColor);
  return sboard;
}

case sf::Event::MouseButtonPressed:
                switch(event.mouseButton.button)
                    case sf::Mouse::Left:
                    {
                        float bposX = sboard.getPosition().x;
                        float bposY = sboard.getPosition().y;
                        cout << "Current Position : ";
                        cout << bposX << " " << bposY << endl;
                    break;
                    }   

for(int i=0; i < sgridSize; i++)
{
    for (int j = 0; j < sgridSize; j++)
    {
        window.draw(sgrid[i][j]);
        sf::FloatRect sgridBounds = sgrid[i][j].getGlobalBounds();
        if(sgridBounds.contains((sf::Vector2f)pointerPos))
        {
            shighlightCell.setPosition(sgrid[i][j].getPosition());
            window.draw(shighlightCell);
            if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
            {
                sgrid[i][j].setFillColor(sf::Color::Green);
            }
        }
    }
}

When I click in rectangle it only displays 1 1, based on my Vector2f position.


回答1:


Assuming I'm reading your code properly, sboard is a sf::RectangleShape. Chances are you actually want the position of the mouse, not this rectangle. Mouse position is given through the static function sf::Mouse::getPosition() which gives coordinates relative to desktop or sf::Mouse::getPosition(window) which will give you the position of the mouse relative to a sf::Window or sf::RenderWindow instance.

I suggest reading through the tutorials on the SFML website while you're learning the basics. This one is immediately useful.



来源:https://stackoverflow.com/questions/25690979/getting-clicked-position-using-sfml

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