Avoid O(n^2) complexity for collision detection

后端 未结 3 1023
迷失自我
迷失自我 2020-12-29 13:42

I am developing a simple tile-based 2D game. I have a level, populated with objects that can interact with the tiles and with each other. Checking collision with the tilemap

相关标签:
3条回答
  • 2020-12-29 14:01

    Why don't you let the tiles store information about what objects occupy them. Then collisions can be detected whenever an object is moved to a new tile, by seeing if that tile already contains another object.

    This would cost virtually nothing.

    0 讨论(0)
  • 2020-12-29 14:09

    Your game already has the concept of a gameplay-related tilemap. You can either co-opt this tilemap for collision detection, or overlay a secondary grid over your playing field used specifically for sprite tracking and collision detection.

    Within your grid, each sprite occupies one or more tiles. The sprite knows which tiles it occupies, and the tiles know which sprites occupy it. When a sprite moves, you only need to check for collisions within the tiles that the sprite occupies. This means no collision detection is necessary at all unless sprites are close enought to occupy the same tiles, and even then, you only need to check for collisions between the sprites that are close together.

    If your gameplay is such that sprites will frequently clump together, you may want to implement your grid as a quadtree to allow each tile to be subdivided and prevent too many sprites from occupying the same grid tile.

    Also, depending on your implementation, you may need to use a slightly larger bounding box to determine tile occupancy than you use to determine collisions. That way you'll be guaranteed that the sprites will overlap and occupy the same tile before their collision boundaries touch.

    0 讨论(0)
  • 2020-12-29 14:16

    You can use quadtree to divide the space and reduce the number of objects you need to check for collision.

    See this article - Quadtree demonstration.

    And perhaps this - Collision Detection in Two Dimensions.

    Or this - Quadtree (source included)

    It may seem - at first glance - that it takes a lot of CPU power to maintain the tree, but it also reduces the number of checks significantly (see the demonstration in th first link).

    0 讨论(0)
提交回复
热议问题