Hey guys, my first post on here, I need help with setting up basic collision with a program I just did up. I downloaded sfml about an hour ago, and I have a cube I can move around, and want it to stop moving, when colliding with a stationary cube. The problem most likely lies within one of the loops, or who knows where, but I've had my fill of tinkering with it.
#include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include <iostream> using namespace std; bool isCollision(int x, int y, int x2, int y2){ //Function I borrowed if (abs(x2 - x) > 20 || abs(y2 - y) > 20) return false; else return true; } int main() { sf::RenderWindow App(sf::VideoMode(800, 600, 32), "My SFML Window"); sf::RenderWindow Warning(sf::VideoMode(400, 225, 32), "WARNING!"); //Window that should open on collision sf::Shape Rect = sf::Shape::Rectangle(0, 0, 20, 20, sf::Color::Red); sf::Shape Rect2 = sf::Shape::Rectangle(50, 0, 70, 20, sf::Color::Blue); while (App.IsOpened()) { sf::Event event; while (App.GetEvent(event)) // I now know an easier way to handle these events, but makes no real difference { if (event.Type == sf::Event::Closed) App.Close(); if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape)) App.Close(); if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Right)) Rect.Move(5.0, 0); if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Left)) Rect.Move(-5.0, 0); if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Down)) Rect.Move(0, 5.0); if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Up)) Rect.Move(0, -5.0); int x = Rect.GetPosition().x; int y = Rect.GetPosition().y; int x2 = Rect2.GetPosition().x; int y2 = Rect2.GetPosition().y; isCollision(x, y, x2, y2); if (isCollision(x, y, x2, y2) == true) { Warning.Clear(sf::Color::White); Warning.Display(); } } App.Clear(); App.Draw(Rect); App.Draw(Rect2); App.Display(); } return EXIT_SUCCESS;
I got the bool isCollision function from a tut I was watching, but the tut was done in allegro, so I scraped from it what I could. (My logic in using his function was that our cubes are the exact same size, and identical in their properties [one moving one stationary]. The problem must lie, I assume, in how I call the function. Any and all help is appreciated