So I recently got into SFML programming, and I need help creating a bool that checks if two rectangles are colliding or overlapping each other.
This is the code so far:
bool collision(sf::Rect rect, sf::Rect rect2){
return rect.getGlobalBounds().intersects(rect2.getGlobalBounds());
}
I'm receiving these errors:
- missing template arguments before 'rect'
- missing template arguments before 'rect2'
- expected primary-expression before ')' token
I am making a platformer and cannot find an efficient way to test collision between the player and the world.
This is the kind of code I want to write for this simple program:
if(collision(rectangle1,rectangle2)){
std::cout << "collision" << std::endl;
}
Any help is appreciated! :)
Here is my code:
#include <SFML/Graphics.hpp>
#include <SFML/Window/Keyboard.hpp>
#include <SFML/Graphics/Rect.hpp>
int main(){
sf::RenderWindow window(sf::VideoMode(800,600),"INSERT_WINDOW_TITLE", sf::Style::Titlebar | sf::Style::Close);
sf::RectangleShape rect1(sf::Vector2f(20.f,20.f));
rect1.setFillColor(sf::Color::Blue);
sf::RectangleShape rect2(sf::Vector2f(20.f,20.f));
rect2.setFillColor(sf::Color::Green);
bool collision(sf::FloatRect r1, sf::FloatRect r2)
{
return r1.intersects(r2, sf::FloatRect());
}
while(window.isOpen()){
sf::Event event;
while(window.pollEvent(event)){
if (event.type == sf::Event::Closed)
window.close();
}
if(sf::Keyboard::isKeyPressed(sf::KeyBoard::W) && collision(rect1,rect2) == false) rect1.move(0.f,-1.f);
if(sf::Keyboard::isKeyPressed(sf::KeyBoard::S) && collision(rect1,rect2) == false) rect1.move(0.f,1.f);
if(sf::Keyboard::isKeyPressed(sf::KeyBoard::A) && collision(rect1,rect2) == false) rect1.move(-1.f,0.f);
if(sf::Keyboard::isKeyPressed(sf::KeyBoard::D) && collision(rect1,rect2) == false) rect1.move(1.f,0.f);
window.draw(rect1);
window.draw(rect2);
window.display();
}
}