I'm trying to duplicate sprites on the screen, but I can't do that without making multiple sprites.
I found somebody else ask the same question but what I am trying to do is, for example, click somewhere in the window and make the sprite appear there. I tried to draw that sprite in two places on the screen (which worked) but I had also added collision for the sprite and the player sprite, which for some reason, did not stop the player from moving into the sprite.
#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();
}
}
As you can see, I added comments to where the "error" occurred. The problem is that only the second sf::RectangleShape had collision and the sprite was being drawn too fast for any real collision (or at least that is what I am guessing). (I'm thinking about duplicating sprites without duplicating code 1000 times) How would I go about fixing this problem?