I'm really sorry of asking such a basic question, but I tried fixing it with searches and the sfml documents and couldn't get it. Also, it's my first sfml/graphics program.
All i want to is for my rectangle to not go out of the screen.
Here's my code.
#include <SFML/Graphics.hpp>
int main()
{
float x= 50, y= 50, width= 20, height= 10, xVid= 800, yVid=600;
float mov= 0.5;
sf::RenderWindow window(sf::VideoMode(xVid, yVid), "SFML works!");
sf::RectangleShape rectangle(sf::Vector2f(width, height));
rectangle.setFillColor(sf::Color::White);
rectangle.setPosition(x, y);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if(event.type== sf::Event::KeyReleased)
{
if(event.key.code== sf::Keyboard:: Escape)
window.close();
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
if(x<0)
x= 0;
else
rectangle.move(-mov,0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
if(x+width>600)
x= 600- width;
else
rectangle.move(mov,0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
if(y<0)
y= 0;
else
rectangle.move(0, -mov);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
if(y+height> 800)
y= 800- height;
else
rectangle.move(0, mov);
}
window.clear();
window.draw(rectangle);
window.display();
}
return 0;
}