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

Author Topic: Sprite within Sprite  (Read 1213 times)

0 Members and 1 Guest are viewing this topic.

WDR

  • Jr. Member
  • **
  • Posts: 82
    • View Profile
Sprite within Sprite
« 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!  :(

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Sprite within Sprite
« Reply #1 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
}
Laurent Gomila - SFML developer

WDR

  • Jr. Member
  • **
  • Posts: 82
    • View Profile
Re: Sprite within Sprite
« Reply #2 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! :)
« Last Edit: July 29, 2013, 08:58:00 am by WDR »

 

anything