I have a spritesheet 900x100 pixels. Each 100x100 pixel block is a shape. I store it using sf::IntRect into an array of sprites with each sprite being a separate shape.
When my program runs, after 2 seconds, a shape appears on screen. When I click it, it disappears and after two seconds it appears again. I can't figure out how to make it so that every time I click it, the next shape will be a randomly selected one.
Do you just want a randomly selected one out of that array?
Try something like
1 2 3 4 5 6 7 8 9
unsignedint index = 0;
...
if (event.type == sf::Event::MouseButtonPressed) {
index = SomeRandomlyChosenNumberBetween1and9..
}
...
window.clear();
window.draw(Shape[index]);
window.display();
I recommend avoiding polling using sf::Mouse::IsButtonPressed for things like this, since it will fire every frame that you're holding the mouse down. Using if (event.type == sf::Event::MouseButtonPressed) you'll only change the index when the user presses the mouse down and it won't be triggered again until the user releases the mouse and pressed down on the mouse again. It'll only fire once per mouse click rather than firing every frame the mouse is held down.
The reason it takes 2 seconds to change is because you have if (clock.getElapsedTime().asSeconds() >= 2). Remove that if you don't want to only check every 2 seconds.
If there is no shape on screen, I want it to wait 2 seconds before showing the next one. But if there is, then I want that shape to stay there until clicked.
Thanks for the code it works perfectly.
For anyone who's isn't clear on what I did:
1 2 3
// Outside of game loop, within main().
//When the program runs for the first time, it assigns a random index number
unsignedint random = rand() % 8;
In my while (window.pollEvent(event)) loop, I added:
1 2 3 4
if (event.type == sf::Event::MouseButtonPressed)
{
random = rand() % 8;
}
Now every time the game starts, there is a random index number, after that, each time a mouse button is pressed it assigns a new random number to the index variable.
And change the .setPosition parameters to: (vector[PosIndex]).
However now, after clicking on a shape, the next shape either takes 2 seconds to appear or appears instantly. They are changing coordinates randomly, just not taking 2 seconds to appear.