Collision Detection and responding to it
NickyAtfat

Hey guys, I'm working on an engine for a 2D action RPG using C++ and the Allegro library. I just discovered this forum so I decided to put forward a problem I have...

I have the code written to find out if one sprite is colliding with another sprite. But if one sprite goes inside something it shouldn't, like the ground, I want it to stop moving.

The problem: the sprites x and y positions are updated based on its velocity x and velocity y valuables. The code to stop the sprite going through the ground looks like this a the moment:

if (onSurface())
{
vY = 0;
}

However if the sprite is traveling too fast (for example after jumping or falling off a ledge) it can end up being stuck inside the ground. ??? Any ideas? I have thought about using an old x and old y value and if the sprite collides, set the x and y values back to the old ones. However I don't think this would work because of the sprite traveling in incrementations of velocity x and y.

I would be really interested to hear how other people solve this and appreciate some help ;)

Thanks,
Nicky

Jonatan Hedborg

The easiest would probably be to check for the future location. That is x+vX, not just x, and then backtrack (back away until they no longer overlap, then stop).

NickyAtfat

Thanks for you response!

Hmm I've been trying to implement that and I'm having trouble with the "backtracking" part... I'm not sure I understand what you mean... Maybe you have an example?

Jonatan Hedborg

Not really. But a non-optimal solution could be something like this (pseudo code)
(This is when colliding with non-moving objects, moving objects is a bit harder.)

Is movingObject.position+movingObject+velocity colliding with staticObject.position?
(
  Do for each point in a line going from movingObject.position to movingObject.position+velocity
    (
       Is currentPosition colliding with staticobject.position?
       (
          //This is the final position of the moving object. Set speed to 0 etc
       )
    )
)

You may want to do this on a per-axis basis oslt, not sure

NickyAtfat

Aha I was forgetting to set the velocity to 0, works fine now.

Thanks very much! :D

Thread #592712. Printed from Allegro.cc