Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Changing displayed images with button presses  (Read 2577 times)

0 Members and 1 Guest are viewing this topic.

csandhmech

  • Newbie
  • *
  • Posts: 3
    • View Profile
    • Email
Changing displayed images with button presses
« on: July 27, 2014, 03:11:39 am »
I have searched and searched for ways to do this but all I found was either nowhere close to what I was doing or simply didnt work. I am a newbie first off, so please bear with me. Between SFML and SFGUI, there has to be an easy way to do this. What I am looking to do is, if you press a button, an image pops up, press a different button and that image goes away and a new one pops up. Each button shows a different image from each other but button 1 always shows image 1, button 2 shows image 2, etc.... For instance a character selection screen: You have 3 characters to choose from, each one having its own button to select them. Once the button of character 1 is pressed, the image of what character 1 looks like shows up. From what I could find, vectors may be the way to go but I cant find anything on just how to do it. If someone could show me the way to go with a detailed explanation, I would greatly appreciate it. Thanks in advance.

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Changing displayed images with button presses
« Reply #1 on: July 27, 2014, 05:04:09 am »
One way could be:

Create a number of sprites - one with each image - and store them all in a vector:
std::vector<sf::Sprite> sprites;

Store which of your images you wish to be displayed in a variable:
unsigned int currentSprite{ 0 };

Change currentSprite to the number of the image that you want to display whenever that button is pressed (it is assumed here that the buttons are mouse buttons and that you test them using events):
if (event.type == sf::Event::MouseButtonPressed)
{
    if (event.mouseButton.button == sf::Mouse::Left)
        currentSprite = 2;
    else if (event.mouseButton.button == sf::Mouse::Right)
        currentSprite = 1;
    else if (event.mouseButton.button == sf::Mouse::Middle)
        currentSprite = 0;
}

Only draw the one sprite necessary:
window.draw(sprites[currentSprite]);


Remember to do the rest of the work! e.g. clear and display the window, do the event loop, load the textures and create the sprites, ensure that currentSprite is never out-of-range, etc..
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

csandhmech

  • Newbie
  • *
  • Posts: 3
    • View Profile
    • Email
Re: Changing displayed images with button presses
« Reply #2 on: July 28, 2014, 01:02:50 am »
Wonderful solution! Thank you very much for your help. It worked quite well. Its a nice easy to change as needed method as well.