Sfml碰撞:当玩家击中一个方块时,他就停止移动
Sfml collision: when the player hits a square, he just stops moving
我决定在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中。
这允许你将玩家向后移动所需的空间,这样物体将不再相交,玩家可以再次移动。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '