Thanks for all the replies. Finally figured it out,here is the updated code.
#include <SFML/Graphics.hpp>
#include <iostream>
bool Collision(sf::RectangleShape square,sf::RectangleShape square2)
{
if(square.getPosition().x + square.getSize().x > square2.getPosition().x &&
square.getPosition().x < square2.getPosition().x + square2.getSize().x &&
square.getPosition().y + square.getSize().y > square2.getPosition().y &&
square.getPosition().y < square2.getPosition().y + square2.getSize().y)
{
std::cout << "collide" << std::endl;
return true;
}
else
return false;
}
int main()
{
sf::RenderWindow window(sf::VideoMode(800,600), "SFML");
window.setFramerateLimit(60);
sf::Clock frameTime;
sf::RectangleShape square(sf::Vector2f(40.f,40.f));
square.setFillColor(sf::Color::Red);
square.setPosition(200.f,500.f);
sf::RectangleShape square2(sf::Vector2f(40.f,100.f));
square2.setFillColor(sf::Color::Green);;
square2.setPosition(275.f,275.f);
sf::Vector2f speed(150.f,150.f);
while(window.isOpen())
{
float dt = frameTime.restart().asSeconds();
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
window.close();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
square.move(speed.x * dt,0.f);
if(Collision(square,square2))
{
square.setPosition(square2.getPosition().x - square.getSize().x,square.getPosition().y);
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
square.move(-speed.x * dt,0.f);
if(Collision(square,square2))
{
square.setPosition(square2.getPosition().x + square2.getSize().x,square.getPosition().y);
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
square.move(0.f,speed.y * dt);
if(Collision(square,square2))
{
square.setPosition(square.getPosition().x,square2.getPosition().y - square.getSize().y);
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
square.move(0.f,-speed.y * dt);
if(Collision(square,square2))
{
square.setPosition(square.getPosition().x,square2.getPosition().y + square2.getSize().y);
}
}
window.clear();
window.draw(square);
window.draw(square2);
window.display();
}
return 0;
}