Collision detection and Sprite animations are the main components of all video games. Snail Bait (the game built in this article series) is no exception. Figure 1 shows the explosion of Snail Bait's running villain after a collision with a bee in the upper left corner.
Figure 1. Practical application of collision detection
In this article, learn how to:
Detecting collisions
Using the HTML5 Canvas context for collision detection
To realize collision detection as Sprite behavior
Handling collisions
Implement sprite animations, such as explosions
Collision Detection Process
Collision detection is a 4-step process, the first step is the actual detection of collisions:
Iterate over the sprite of the game
Excluding sprite that are not suitable for collision detection
Detecting the collision between candidate Sprite
Handling collisions
Collision detection may require a high amount of computation, so it is important to avoid detecting sprite that are not likely to collide. For example, when the sprite exploded, Snail bait runners would pass through the other sprite. Since it takes less time to check whether a sprite is exploding than to perform collision detection, Snail bait excludes explosions sprite from collision detection.
We'll start with an overview of collision detection techniques.
Collision Detection Technology
There are many ways to detect collisions between sprite. The three popular technologies available (ranked in order of sophistication and complexity) are:
Boundary area (called the bounding body in the 3D game)
Light projection
Separation axis theorem (separating axis theorem)
Use collision detection in boundary areas to detect intersections of circles or polygons. In the example in Figure 2, the small circle is the boundary area that represents a sprite (a ball), and the large circle is the sprite boundary area of a bucket, which is larger than the ball. When two circular boundary areas intersect, the ball falls into the bucket.
Figure 2. Boundary area: A collision between circles