Search code examples
c++sfml

Sfml collision: when the player hits a square, he just stops moving


I decided that I wanted to make a collision test in c++ and sfml. But when the player hits the square you can't move anymore. I'm not having any issues with how to do collision, but what to do when I actually GET a collision.

Here's my code:

#include <SFML/Graphics.hpp>
#include <iostream>
#include <thread>

using namespace std;
using namespace sf;

RenderWindow window(VideoMode(500, 500), "SFML");

RectangleShape r1;
RectangleShape r2;

void collision(){

r1.setSize(Vector2f(50.0, 50.0));
r2.setSize(Vector2f(50.0, 50.0));

r1.setPosition(20, 200);
r2.setPosition(420, 200);

r1.setFillColor(Color::Red);
r2.setFillColor(Color::Blue);
}

int main(){

collision();

while (window.isOpen()){
    Event event;

    while (window.pollEvent(event)){

        if (event.type == Event::Closed){
            window.close();
        }
    }

        if (Keyboard::isKeyPressed(Keyboard::W))
            if (!r1.getGlobalBounds().intersects(r2.getGlobalBounds()))
                r1.move(0.0, -0.05);

        if (Keyboard::isKeyPressed(Keyboard::A))
            if (!r1.getGlobalBounds().intersects(r2.getGlobalBounds()))
                r1.move(-0.05, 0.0);

        if (Keyboard::isKeyPressed(Keyboard::S))
            if (!r1.getGlobalBounds().intersects(r2.getGlobalBounds()))
                r1.move(0.0, 0.05);

        if (Keyboard::isKeyPressed(Keyboard::D))
            if (!r1.getGlobalBounds().intersects(r2.getGlobalBounds()))
                r1.move(0.05, 0.0);

    window.draw(r2);
    window.draw(r1);

    window.display();
    window.clear();
}
}

Once again, I would like to know how to properly move your player and make it so that when you can't enter a object.

Thanks in advance!

PS. Please don't tell me "uh, your code is so horribleee. your bracketss suck ablahb..." I know. It's a little messy alright?

Thanks.


Solution

  • The problem at Jack Edwards's answer is intersection control is before move command. But firstly sprite must move and after comes intersection control. If there is intersection, sprite must move back.

    if (Keyboard::isKeyPressed(Keyboard::W)){
                    r1.move(0.0, -0.05);
                if (r1.getGlobalBounds().intersects(r2.getGlobalBounds()))
                    r1.move(0.0, +0.05);}