Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <iostream>
- using namespace std;
- #include <cmath>
- class Vector2{
- public:
- float x, y;
- Vector2();
- Vector2(float a, float b);
- float getMagnitude();
- Vector2 getNormalised();
- void normalised();
- };
- Vector2::Vector2(){
- x = 0;
- y = 0;
- }
- Vector2::Vector2(float a, float b){
- x = a;
- y = b;
- }
- float Vector2::getMagnitude(){
- float m = (float)sqrtf(x*x+y*y);
- return m;
- }
- void swapHeadings(Vector2 *a, Vector2 *b){
- Vector2 t = *a;
- a->x = b->x;
- a->y = b->y;
- b->x = t.x;
- b->y = t.y;
- }
- void doCollision(Vector2 *a, Vector2 *b, int r1, int r2, bool *collided){
- Vector2 dist(b->x-a->x, b->y-a->y);
- if (dist.x < 0){
- dist.x = dist.x*-1;
- }
- if (dist.y < 0){
- dist.y = dist.y*-1;
- }
- float magni = dist.getMagnitude();
- if (r1+r2 >= magni){
- *collided = true;
- }
- else if (r1+r2 < magni){
- *collided = false;
- }
- }
- int main(){
- sf::RenderWindow window{{640,480}, "Collision Test"};
- window.setVerticalSyncEnabled(true);
- //window.setFramerateLimit(60);
- bool running = true;
- bool collided = false;
- Vector2 v1(0, 100);
- Vector2 v2(640, 100);
- Vector2 hV1(1,1);
- Vector2 hV2(-1,1);
- doCollision(&v1, &v2, 5, 5, &collided);
- sf::Texture t;
- if (!t.loadFromFile("icon.png")) return -1;
- sf::Sprite spr{t};
- spr.setPosition({100,100});
- while (running){
- v1.x += hV1.x*2;
- v1.y += hV1.y*2;
- v2.x += hV2.x*2;
- v2.y += hV2.y*2;
- if (v1.x <= 0){
- hV1.x = 1;
- }
- if (v1.x >= 630){
- hV1.x = -1;
- }
- if (v1.y <= 0){
- hV1.y = 1;
- }
- if (v1.y >= 470){
- hV1.y = -1;
- }
- if (v2.x <= 0){
- hV2.x = 1;
- }
- if (v2.x >= 630){
- hV2.x = -1;
- }
- if (v2.y <= 0){
- hV2.y = 1;
- }
- if (v2.y >= 470){
- hV2.y = -1;
- }
- doCollision(&v2, &v1, 5, 5, &collided);
- cout<<"Collided: "<<collided<<endl;
- if (collided){
- swapHeadings(&hV1, &hV2);
- }
- sf::Event event;
- sf::RectangleShape rect1{{10,10}};
- sf::RectangleShape rect2{{10,10}};
- rect1.setFillColor(sf::Color::White);
- rect2.setFillColor(sf::Color::Red);
- rect1.setPosition({v1.x, v1.y});
- rect2.setPosition({v2.x, v2.y});
- while (window.pollEvent(event)){
- if (event.type == sf::Event::Closed){
- running = false;
- }
- }
- window.clear();
- window.draw(rect1);
- window.draw(rect2);
- //window.draw(spr);
- window.display();
- }
- window.clear();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement