Pergunta

I'm learning SFML right now, and I have just managed to implement some basic jumping and gravity. However, I can't figure out how to put in collisions because I need to also detect which side of an object is being hit. For example, I need upward movement to stop if it hits the bottom of an object, downward to stop if it hits the top, and left or right movement if it just hits a side. These would just be rectangular objects, so I wouldn't have to program weird for circles or unnatural shapes, just the 4 sides. Thanks!

Foi útil?

Solução

There are a number of different ways to do this, some more complex (and efficient) than others. For your sake, I would begin with simply putting a "bounding box" around your character. This bounding box will move everywhere that your character goes and should surround him or her. Whenever this bounding box intersects with a solid object, there is your collision.

Here's where the fun comes in:

  1. What does "intersects" mean? A lot of things. You can write a function to find out if two shapes are intersecting, or use a function from SFML, or use some sort of physics library (like Box2D).
  2. How do you stop a character from passing through? Find out how far they will intersect (you check collision BEFORE you move the character), then make it so the character only moves to the bounds of that solid object.

This is an extremely simplified explanation. Collision detection and handling are difficult. Your best bet is to spend a lot of time DETECTING the collision then worrying about how to handle the collision. Many beginners try these at the same time and get frustrated.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top