I have a spritesheet(900x100) with of different colored shapes each size 100x100. I am trying to code a program such that, after every 2 seconds, one random sprite appears on screen. If I click, it should disappear and after 2 seconds another random shape should appear. If I don't, it should continue to show that image.
Using IntRect, I am able to cut out individual shapes out of the spritesheet and display them. I thought that in the IntRect parameters:
Shape.setTextureRect(sf::IntRect(0, 0, 100, 100));
I could replace the first 0, like this:
Shape.setTextureRect(sf::IntRect(((rand() % 8) * 100), 0, 100, 100));
and after 2 seconds, it would show me a new random sprite. However, after 2 seconds, the window shows what looks like a bunch of random shapes playing really fast one after the other, nothing and then 2 seconds later it repeats.
If I can't get the random images to work properly I don't think I'll be able to do the mouse events.
Here is my code so far: main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480), "Tile Game");
sf::Clock clock;
sf::Time timer;
sf::Texture shapeSpriteSheet;
sf::Texture Background;
sf::Sprite bg;
sf::Sprite Shape;
srand(time(NULL));
Background.loadFromFile("bg.png");
bg.setTexture(Background);
shapeSpriteSheet.loadFromFile("shapes.png");
shapeSpriteSheet.setSmooth(true);
Shape.setTexture(shapeSpriteSheet);
Shape.setPosition(sf::Vector2f(192, 146));
while (window.isOpen())
{
sf::Event event;
window.draw(bg);
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
timer = clock.getElapsedTime();
if (timer.asSeconds() >= 2)
{
Shape.setTextureRect(sf::IntRect(((rand() % 8) * 100), 0, 100, 100));
window.draw(Shape);
if (timer.asSeconds() > 2.1)
clock.restart();
}
window.display();
}
return 0;
}
Update:
I've finally made it so that, every 2 seconds a sprite appears, on click it disappears. Now Im working on making every sprite randomly selected
New code:
if (clock.getElapsedTime().asSeconds() >= 2)
{
shapeVisible = true;
Shape[0].setPosition(sf::Vector2f(192, 146));
window.draw(Shape[0]);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
if (Shape[0].getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))))
{
clock.restart();
}
}
}