【问题标题】:Sfml collision: when the player hits a square, he just stops movingSfml 碰撞:当玩家撞到一个方块时,他只是停止移动
【发布时间】:2015-06-24 12:45:01
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      例如:

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

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

      【讨论】:

      • 还是不行!玩家只是冻结!或者它有效,但并非总是如此。
      • 好的,所以我发现为什么玩家有时会卡住是因为他进入了立方体。当他这样做时,按任何步行键都会将他弹出到别处。如何让他不进入魔方?
      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      相关资源
      最近更新 更多