SFML community forums

Help => Graphics => Topic started by: WDR on July 29, 2013, 07:44:31 am

Title: Sprite within Sprite
Post by: WDR on July 29, 2013, 07:44:31 am
How do I create the bounding boxes and set the condition such that a sprite when given user input moves in 2D space but within the the boundaries of another sprite? Here's my code so far:

sf::FloatRect bound1 = sprite1.getGlobalBounds();
sf::FloatRect bound2 = sprite2.getGlobalBounds();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        sprite2.move(0.f, speed * time);
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
        sprite2.move(0.f, -speed * time);
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        sprite2.move(speed * time, 0.f);
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        sprite2.move(-speed * time, 0.f);

Please help!  :(
Title: Re: Sprite within Sprite
Post by: Laurent on July 29, 2013, 07:55:31 am
if ((bounds2.left < bounds1.left) ||
    (bounds2.top < bounds1.top) ||
    (bounds2.left + bounds1.width > bounds1.left + bounds1.width) ||
    (bounds2.top + bounds2.height > bounds1.top + bounds1.height))
{
    // sprite2 crosses boundaries of sprite1, don't move it
}
Title: Re: Sprite within Sprite
Post by: WDR on July 29, 2013, 08:56:21 am
OHHH! Thank you so much, Laurent! I've been losing my hair over this! Do you know the feeling when you look at a solution and realize that it is so obvious and curse yourself that you weren't able to solve it in the first place? Well... I have it now!  :-[

Anyways, thanks a lot for the help! Cheers! :)