Tuesday, April 2, 2019

slick - How do I handle collision detection so fast objects are not allowed to pass through walls?


I'm creating a 2d sidescrolling shooter, and I'm having a little trouble with collision detection for the bullets. Everything including the bullets are objects with their own polygons / update methods.


The trouble is that bullets go fast, and at 60 frames per second (what the game runs at) a bullet will often skip right through a wall -- since it moves more than the width of the wall during in the update interval -- and continue happily on its way since the polygons will never actually overlap.



What can I do about this? The only thing I've been able to come up with is to draw a line from the old position to the new position and do collision detection on that, but line drawing for collision detection is recommended against by the slick2d documentation. How can I solve this?



Answer



The standard approaches are (pick one):



  1. Increase your boundary width AND/OR reduce the maximum speed of your bullet so that it can never jump through a wall in a single update (requiers a bit of Pythagoras to figure out the maxium distances / minimum boundary widths);

  2. Perform continuous collision detection (CCD), usually by raycasting to detect collision with linear (2) or planar (3D) surfaces ahead of the moving object. This is more expensive, but is a more well-rounded solution. Raycasting against 2D lines is pretty basic, but you do need to define all your boundaries as straight-edge polygons in this case.


For that matter, you can model your bullets as rays instead -- if that fits with the look & feel of your game, as in left4kdead. That way you don't need to approximate bullets as rays, because they already are rays. From the viewpoint of looks, this can look decent if you draw the line with a brighter spot on the bullet end, or just draw the line as a gradient from light (bullet end) to dark (tail end), giving it an appearance of motion.


I would agree that under most circumstances, using graphics for collision detection is a bit misguided, however pixel-perfect collision detection is exactly that, and is an accepted technique. I guess it all depends on what you want to achieve, and how quickly. If you don't need a very fast game with many bodies + action, go for it. Else better to use one of the approaches I outlined above.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...