我编写了一个简单的程序,屏幕上有两个立方体,一个用户可以移动,另一个是静止的。我刚开始使用 sfml,从未接触过碰撞,所以这对我来说是全新的。在我的代码中,我的目标是在用户将立方体引导到静止的立方体时弹出一个警告窗口。然而,问题是,一旦我启动程序,警告窗口就会出现,即使它在 if 循环中。这是我的代码:
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
using namespace std;
bool isCollision(int x, int y, int x2, int y2){ // borrowed function, all credits go to whom ever made it
if (abs(x2 - x) > 20 || abs(y2 - y) > 20)
return false;
else
return true;
}
int main()
{
sf::RenderWindow App(sf::VideoMode(800, 600, 32), "My SFML Window");
sf::RenderWindow Warning(sf::VideoMode(400, 225, 32), "WARNING!");
sf::Shape Rect = sf::Shape::Rectangle(0, 0, 20, 20, sf::Color::Red);
sf::Shape Rect2 = sf::Shape::Rectangle(50, 0, 70, 20, sf::Color::Blue);
while (App.IsOpened())
{
sf::Event event;
while (App.GetEvent(event)) // I now know the shorter way to handle events, just haven't edited it yet. No functional difference
{
if (event.Type == sf::Event::Closed)
App.Close();
if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape))
App.Close();
if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Right))
Rect.Move(5.0, 0);
if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Left))
Rect.Move(-5.0, 0);
if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Down))
Rect.Move(0, 5.0);
if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Up))
Rect.Move(0, -5.0);
}
int x = Rect.GetPosition().x;
int y = Rect.GetPosition().y;
int x2 = Rect2.GetPosition().x;
int y2 = Rect2.GetPosition().y;
isCollision(x, y, x2, y2);
if (isCollision(x, y, x2, y2) == true) // if loop that I am messing up somehow
}
Warning.Clear(sf::Color::White);
}
App.Clear();
App.Draw(Rect);
App.Draw(Rect2);
App.Display();
}
return EXIT_SUCCESS;
}
我从正在观看的 tut 中获得了 bool isCollision 函数,但是 tut 是在 allegro 中完成的,所以我尽可能地从中刮取。(我使用他的函数的逻辑是我们的立方体大小完全相同,并且它们的属性相同[一个移动一个静止]。我认为问题必须在于我如何调用该函数。任何和所有的帮助都很大赞赏