如何在屏幕上多次复制一个精灵,每个精灵具有相同的代码?

时间:2018-12-27 02:02:45

标签: c++ sprite sfml

我正在尝试在屏幕上复制精灵,但是如果不制作多个精灵,我将无法做到这一点。

我发现有人问同样的问题,但是我想做的是,例如,单击窗口中的某个位置并使精灵显示在其中。我试图在屏幕上的两个位置绘制该精灵(起作用),但是我还为该精灵和播放器精灵添加了碰撞,由于某种原因,这并没有阻止播放器移入该精灵。

 #include <SFML/Graphics.hpp>
 #include <SFML/Window/Keyboard.hpp>

bool collision(sf::FloatRect r1, sf::FloatRect r2)
{
    sf::FloatRect intersection;
    return r1.intersects(r2, intersection);
}

bool collision(sf::Shape const & r1, sf::Shape const & r2)
{
    return collision(r1.getGlobalBounds(), r2.getGlobalBounds());
}
int main(){
sf::RenderWindow window(sf::VideoMode(800,600),"INSERT_WINDOW_TITLE", 
sf::Style::Titlebar | sf::Style::Close);
sf::RectangleShape player(sf::Vector2f(20.f,20.f));
player.setFillColor(sf::Color::Blue);
sf::RectangleShape rect(sf::Vector2f(20.f,20.f));
rect.setFillColor(sf::Color::Red);
int mousex = 400;
int mousey = 240;
rect.setPosition(400,240);
while(window.isOpen()){
    sf::Event event;
    if(collision(player,rect) == false){
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) 
player.move(0.f,-1.f);
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) 
player.move(0.f,1.f);
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) 
player.move(-1.f,0.f);
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) 
player.move(1.f,0.f);
    }
    if(sf::Mouse::isButtonPressed(sf::Mouse::Left)){
        mousex = sf::Mouse::getPosition().x;
        mousey = sf::Mouse::getPosition().y;
    }
    while(window.pollEvent(event)){
         if (event.type == sf::Event::Closed)
            window.close();
    }
    window.clear(sf::Color::Black);
    window.draw(player);
rect.setPosition(400,240); // did not have any collision with this rect
    window.draw(rect);
rect.setPosition(mousex,mousey); // I set this position after the 
previous one, which is why it HAD collision
    window.draw(rect);
    window.display();
}
}

如您所见,我在“错误”发生的位置添加了注释。问题是只有第二个sf :: RectangleShape 发生碰撞,并且精灵被绘制得太快而无法进行任何真实的碰撞(或者至少这是我所猜测的)。 (我正在考虑在不重复代码1000次的情况下复制sprites)如何解决此问题?

1 个答案:

答案 0 :(得分:1)

问题是每个循环仅检查一次碰撞。因此,如果您两次绘制矩形,则其中只有一个会发生碰撞。要解决此问题,您应该检查

if(collision(player,rect) == false)

,顺便说一下,可以缩写为

if(!collision(player,rect))
再次

更改矩形在此行上的位置后:

rect.setPosition(mousex,mousey); // I set this position after the previous one, which is why it HAD collision