Best collision detection in your opinion?

6 posts

Flag Post

I’ve always used the hitTest, but I understand this is something of a debate amongst experienced programmers, so I’m curious as to how you would do collision detection when a character walks into a wall?

What if the walls were tile-based squares?
What if the character had a variable hitbox?
And what would you do in the situation of the player’s hitbox changing and going through a wall when a moment ago it was not?

 
Flag Post

Much depends on the kind of game you’re trying to make and just how much precision you need. For example, if your game has a top-down point of view, and the character is generally round shaped, doing a hitTest on the character would be very inaccurate. For a sidescroller, calling hitTest on the character itself is not a good idea because there are some positions where the character is wider than in other positions; e.g., when the character is walking and his arms are to the front and back of his body. This would definitely be a case where the hit box would change in size if you use the character for collision testing.

A better idea may be to have players control a fixed-size invisible collision box. On each frame, position the character image over the collision box so that it looks like the player is controlling the character directly.

If your walls are tile-based, you may check for collision against each tile, although this may be more resource-intensive than necessary. You may also do some pre-processing at the beginning of each scene and generate collision boxes for contiguous tiles.

If you need pixel-perfect collision testing, do it only if the hitTest indicates that a collision was made. That way, you won’t have to call a resource-hungry algorithm unless you really have to.

Again, depending on how your game looks and plays, a different solution may be required. If the character uses melee weapons, for instance, you’ll need to check collision separately for the character and the weapon.

 
Flag Post

I never use hitTest or hitboxes, do it all by maths…storing the size & shape of each object.

 
Flag Post
Originally posted by Amibtious:

I never use hitTest or hitboxes, do it all by maths…storing the size & shape of each object.

Is that more efficient?

 
Flag Post

I believe it’s quite a lot more efficient yeah.

 
Flag Post

Yeh, math is the way to go. I’ve stolen borrowed a lot of xCollideY code over the years. :D (e.g. circle to rect, rect to rect, circle to circle, rotated rect to rotated rect, ray to rotated rect, line to circle, etc)

For object collision against a grid, if the object will always be smaller than the grid, there is some really really simple math to check collisions that is pretty efficient. Even if the bounding size changes (as long as it remains smaller than a tile width/height, you are good).