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

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

本文关键字:方块 一个 移动 碰撞 玩家 Sfml      更新时间:2023-10-16

我决定在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。请不要告诉我"嗯,你的代码太可怕了。你的括号太棒了……"我知道。有点乱,好吗?

谢谢。

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

你的问题是,只有当玩家的边界与第二个对象的边界不相交时,你才允许玩家移动,所以当你第一次与对象碰撞时,你不能再移动到它的边界之外。

你需要做的是当玩家与物体碰撞时将其向后移动。

例如:

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中。

这允许你将玩家向后移动所需的空间,这样物体将不再相交,玩家可以再次移动。