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

Author Topic: Variable Sprite? Maybe an Array?  (Read 2137 times)

0 Members and 1 Guest are viewing this topic.

5gum

  • Newbie
  • *
  • Posts: 27
    • View Profile
Variable Sprite? Maybe an Array?
« on: November 26, 2013, 06:43:25 pm »
Hey guys,
I'm beginner in SFML so please don't be too strict ;)

If I press the right Key for example, a sprite moves.

vehicle.move(speed,0);
 

Nothing special.
But now I want to create a new Sprite and according to which sprite I choose (by mouse click), I want that the correct sprite moves. To see which sprite was taken I've got a simple variable (int choose=0 if sprite 1 was taken and choose=1 if sprite 2 was taken).

The easiest way to find out which sprite should be moved is

if(choose==0)
{
...
}

if(choose==1)
{
...
}
 


But in that codes would stand exactly the same. That's not really effective. So can I create a sprite like

sf::Sprite vehicle[2](vehicle1,vehicle2)
...
vehicle[choose].move(speed,0)
 

Sorry, I know the code is wrong, I'm not really good at using arrays.
Or is there any other simple solution?

Thanks,
5gum

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
Re: Variable Sprite? Maybe an Array?
« Reply #1 on: November 26, 2013, 06:48:31 pm »
Keep a STL container with all the sprites:
std::vector<sf::Sprite> sprites;
sprites.push_back(...);

To choose one sprite, check for every one if the mouse position is located inside (do this upon a sf::MouseButtonPressed event):
sf::Sprite* chosenOne = nullptr;
...
for (sf::Sprite& sprite : sprites)
{
    if (/* mouse inside sprite*/)
        chosenOne = &sprite;
    // Hint: look at sf::Event variable,
    // sf::FloatRect::contains() and sf::Sprite::getGlobalBounds()
}

Then move the selected sprite:
if (chosenOne)
    chosenOne->move(...);
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

5gum

  • Newbie
  • *
  • Posts: 27
    • View Profile
Re: Variable Sprite? Maybe an Array?
« Reply #2 on: November 26, 2013, 07:11:20 pm »
Thanks, it works ;D