SFML community forums

Help => General => Topic started by: Christopher Jozwiak on December 13, 2012, 03:48:20 am

Title: Collision detection sfml 2.0
Post by: Christopher Jozwiak on December 13, 2012, 03:48:20 am
How would i perform a simple box collision detection in sfml?
Title: Re: Collision detection sfml 2.0
Post by: Jebbs on December 13, 2012, 04:14:05 am
The sf::Rect class has the methods Rect.contains and Rect.intersects, so for basic collision detection I would say that's a good place to start.
Title: Re: Collision detection sfml 2.0
Post by: eXpl0it3r on December 13, 2012, 10:11:56 am
Maybe my small example (https://github.com/eXpl0it3r/Examples/blob/master/SFML/SimpleAABB.cpp) could give you some insights. ;)
But keep in mind that it's not finished at all.
Title: Re: Collision detection sfml 2.0
Post by: Christopher Jozwiak on December 14, 2012, 01:13:26 am
Okay what I'm trying to do is make a classic Snake game.  I think i would need to use something like object.GetGlobalBounds().contains().  Then I'm unsure what to put in the contains function.  I put in a number and a point?  What would the point be?
Title: Re: Collision detection sfml 2.0
Post by: eXpl0it3r on December 14, 2012, 02:13:04 am
You should start using the documentation (http://www.sfml-dev.org/documentation/2.0/), which explains what a class/function does.

The contains() (http://www.sfml-dev.org/documentation/2.0/classsf_1_1Rect.php#aa8a5364c84de6dd5299f833b54e31ef1) function either takes 2 floats or a sf::Vector2f and simply checks if a point (defined by the 2 floats or the sf::Vector2f) is within the sf::Rect that is returned by getGlobalBounds() (http://www.sfml-dev.org/documentation/2.0/classsf_1_1Sprite.php#a203d2d8087bfdca2ebc3c0485cdb7409), which essentially the bounding box of the sprite, describe in the 'world' coordinates.
Title: Re: Collision detection sfml 2.0
Post by: Christopher Jozwiak on December 14, 2012, 03:04:59 am
Okay so I tried
if (object.getGlobalBounds().intersects( player.getGlobalBounds())){
            
            touching = true;
         }
         if (touching == true){
            player.move(0,0);
         }


:-\
Title: Re: Collision detection sfml 2.0
Post by: FRex on December 14, 2012, 03:51:07 am
move(0,0) moves the object 0 pixels to the right and 0 pixels down = nothing.
Title: Re: Collision detection sfml 2.0
Post by: Christopher Jozwiak on December 14, 2012, 03:51:32 am
Never mind.  Made a statement print out on the command line if the collision was true.  I just think my player.move method needs to be changed.  When the event polls i think it overruns the collision and the player keeps moving despite the player.move(0,0).
Title: Re: Collision detection sfml 2.0
Post by: kryton9 on March 18, 2013, 05:23:12 am
Maybe my small example (https://github.com/eXpl0it3r/Examples/blob/master/SFML/SimpleAABB.cpp) could give you some insights. ;)
But keep in mind that it's not finished at all.

Thanks, that is a great example to study!