Advertisement
Felanpro

Collision Detection with Bounding Boxes SFML

Apr 6th, 2019
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <SFML/Graphics.hpp>
  4. #include <SFML/Window.hpp>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     sf::RenderWindow window(sf::VideoMode(800, 600), "Project");
  11.  
  12.     sf::RectangleShape player;
  13.     sf::RectangleShape projectile;
  14.     player.setSize(sf::Vector2f(50, 50));
  15.     projectile.setSize(sf::Vector2f(50, 50));
  16.     player.setFillColor(sf::Color::Green);
  17.     projectile.setFillColor(sf::Color::Red);
  18.     player.setPosition(300, 400);
  19.     int x = 370; int y = 400;
  20.     projectile.setPosition(x, y);
  21.     sf::FloatRect boundingBox = player.getGlobalBounds();
  22.  
  23.     sf::Event event;
  24.     while (window.isOpen())
  25.     {
  26.         while (window.pollEvent(event))
  27.         {
  28.             if (event.type == sf::Event::Closed)
  29.                 window.close();
  30.  
  31.             if (event.type == sf::Event::KeyPressed)
  32.             {
  33.                 if (event.key.code == sf::Keyboard::Right)
  34.                     x++;
  35.                 else if (event.key.code == sf::Keyboard::Left)
  36.                     x--;
  37.             }
  38.         }
  39.         projectile.setPosition(x, y);
  40.         sf::FloatRect otherboundingbox = projectile.getGlobalBounds();
  41.  
  42.         if (boundingBox.intersects(otherboundingbox))
  43.             cout << "The two bodies are colliding" << endl;
  44.  
  45.         window.clear(sf::Color::White); //Clear
  46.  
  47.         window.draw(player);
  48.         window.draw(projectile);
  49.  
  50.         window.display(); //Display
  51.     }
  52.  
  53.     int pause; cin >> pause; //Pause the program
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement