问题
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