SFML community forums

Help => General => Topic started by: Leltoson on May 05, 2016, 09:29:21 pm

Title: Help with basic collisions
Post by: Leltoson on May 05, 2016, 09:29:21 pm
What is the most basic form of writing an if statement to detect a collision?

I have two sprites and I basically want one sprite to be moved along by the other (The other sprite has predefined movement behaviour whilst the other sprite is moved by the arrow keys on the keyboard.

Imagine it like the player jumping onto the roof of an already moving spaceship.

Please let me know if you require any more information from me, I am happy to provide this for my space game.
Title: Re: Help with basic collisions
Post by: Erdrick on May 06, 2016, 04:19:48 am
Hi Leltoson,

Here is one way, to see if the boundaries of a sprite contains the corner of another sprite

if (m_sprite.getGlobalBounds().contains(m_sprite2.getPosition()))
Title: Re: Help with basic collisions
Post by: Brax on May 06, 2016, 05:28:02 pm
Or better, check if boundry of a sprite intersects wtih a boundry od another sprite:

if (aSprite.getGlobalBounds().intersects(aSprite2.getGlobalBounds()))
{
  // apply rest of magic here.
}
Title: Re: Help with basic collisions
Post by: Leltoson on May 06, 2016, 09:00:21 pm
With intersects it did not work. With contains it did as so:

   if (player.getGlobalBounds().contains(spaceship.getPosition()))
      {
         std::cout << "testing collision" << std::endl;
                        player.move(x=relative to spaceship speed?, 0);
      }

I am now currently struggling with setting it so when the player is on top of the spaceship it is riding it at the same speed? It moves along with the already pre determined / automated / ai movement of the spaceship.
Title: Help with basic collisions
Post by: Erdrick on May 07, 2016, 01:39:20 am
Hi just fyi the intersects function should be a better solution than what I proposed. 

Its worth making that work since mine only tests one point

Sent from my SGH-M919 using Tapatalk
Title: Re: Help with basic collisions
Post by: Leltoson on May 07, 2016, 03:17:48 am
I got it working actually:

 if (player.getGlobalBounds().intersects(spaceship.getGlobalBounds()))
      {
         std::cout << "testing collision" << std::endl;
                        player.move(x=relative to spaceship speed?, 0);
      }
Title: Re: Help with basic collisions
Post by: Erdrick on May 08, 2016, 02:22:15 am
Nice!  Its great to hear when a problem was solved and how.
Title: Re: Help with basic collisions
Post by: Leltoson on May 08, 2016, 05:52:42 pm
I did not end up using this in my game in the end, but I learnt a lot by trying either how. :D