# Circle-line segment collision resolution

I'm trying to make a side-scrolling game using this method and I'm having some trouble getting it to behave right. The collision shapes consist of multiple connected line segments and I'm checking them one at a time in order from first to last, so in one direction the collisions are resolved in the wrong order and the circle can't move over the connection point.

Is there a way of fixing this that isn't a hack, or should I try preventing the collision from happening in the first place instead?

ETA: The circle is moved straight up if the overlapping line segment is below and not too steep (approx. 50 degrees maximum) to enable it to move on slopes without resistance. In all other cases, the minimum displacement vector is used to resolve the collision.

• Could you had some details about how you resolve the collisions please ? Commented Oct 8, 2014 at 20:21

I think the only true non-hack way to do this is to directly solve for collision between the object (rectangle, here) and the area/volume swept by the moving object (circle).

In many applications that's overkill, in some it's paramount - your decision. I'll assume you're OK with hacks for the rest.

What you've described here (esp. your choice to bump "straight up") suggests a platformer (beyond just being a side-scroller), in which case a very simple first-pass hack might be to check the "top" segment first. That's often the most important surface, so you might get reasonably good behavior with this alone.

Another naive hack, if your game has the spare cycles, would be to approximate the direct solution by interpolating across the desired motion. Then just use the final non-colliding position as the result. Something like this:

Then if you want sliding along an edge, you could record the remaining distance parallel to that surface and use it to kick off another motion with checks. Like so:

There are of course a lot of ways to handle collision, most of them far more clever than what I describe here, but perhaps this will give you some ideas about how to progress.

• Checking the top segment first doesn't work in all cases, since the collision shapes are not always rectangles (I probably should have made that more obvious in the image) and the segment that is blocking movement could be the one on top. Instead, I saved the last "walkable" segment and checked against that first on the next frame. It's not a particularly elegant solution, but it seems to work well enough. I'll look into swept circles if I ever need more precision, thanks.
– grue
Commented Oct 9, 2014 at 9:19