Sfml碰撞:当玩家击中一个正方形时,他就会停止移动

时间:2015-06-24 12:45:02

标签: c++ sfml

我决定在c ++和sfml中进行碰撞测试。但是当玩家击中广场时你就不能移动了。我对如何进行碰撞没有任何问题,但在实际发生碰撞时该怎么办。

这是我的代码:

#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();
}
}

再一次,我想知道如何正确移动你的播放器并使其成为当你无法输入物体时。

提前致谢!

PS。请不要告诉我&#34;呃,你的代码真是太可怕了。你的支架吮吸了阿拉伯...&#34;我知道。这有点凌乱吗?

感谢。

2 个答案:

答案 0 :(得分:2)

Jack Edwards的回答是交叉控制在移动命令之前的问题。但首先精灵必须移动并且在交叉控制之后。如果有交叉点,精灵必须向后移动。

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

答案 1 :(得分:1)

你的问题是你只允许你的玩家移动,如果它的边界不与第二个物体的边界相交,那么当你第一次碰撞物体时你就不能再移动了它的界限。

您需要做的是在播放器与物体碰撞时将其移回。

例如:

if (Keyboard::isKeyPressed(Keyboard::W)) {
    sf::FloatRect& intersection;
    if (r1.getGlobalBounds().intersects(r2.getGlobalBounds(), intersection) {
        r1.move(0.0, intersection.height);
    }
    else {
        r1.move(0.0, -0.05);
    }
}

intersects方法允许您传入对sf :: Rect的引用,如果玩家的边界与第二个对象的边界相交,则交集将存储在rect中。 / p>

这允许您将玩家向后移动所需的空间,以便对象不再相交,玩家可以再次移动。