Hello
I am trying to move a sf::RectangleShape only when the user clicks the mouse over it and then moves it until the mouse is pressed. I am having some problem with this.
Here's my code
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480, 32), "TEST");
sf::RectangleShape shape(sf::Vector2f(30.0f, 30.0f));
shape.setFillColor(sf::Color::Red);
shape.setPosition(sf::Vector2f(100.0f, 200.0f));
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if(event.key.code == sf::Keyboard::Escape)
window.close();
break;
}
}
sf::Vector2f mousePos = (sf::Vector2f)sf::Mouse::getPosition(window);
sf::Vector2f shapePos = shape.getPosition();
std::cout << mousePos.x << ", "<< mousePos.y << std::endl;
if(mousePos.x >= shapePos.x && mousePos.x <= shapePos.x + shape.getGlobalBounds().width
&& mousePos.y >= shapePos.y && mousePos.y <= shapePos.y + shape.getGlobalBounds().height)
if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
shape.setPosition(mousePos.x, mousePos.y);
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
How do I rectify my code to make it work correctly?
Thanks