Flash Game Development with Flex and Actionscript - Collision Detection

Article by Matthew Casperson (4,877 pts ) , published Nov 6, 2009

In part 5 we added some enemies and gave the player the ability to fire it weapons. In part 6 we will add collision detection to allow the player to actually shoot the enemies.

Collision detection is the ability to detect when two objects have collided, and then react appropriately. In part 5 we gave the player the ability to fire weapons at the oncoming enemies. The only problem was that these bullets just passed right through the enemies. In part 6 we will add the necessary code to implement collection detection, which will allow us to shoot the enemies down.

Collision detection is one of those seemingly simple concepts that can be incredibly difficult to implement. You will find entire books devoted to the topic of testing for intersections between 2D and 3D shapes. Fortunately for us our collision detection will be quite simple. Each object on the screen will have a rectangular area in which collisions will be detected (the "collision area"). For simplicity this area will be the same as the size of the underlying graphic that is used to display the sprite on the screen. Once these rectangles overlap we will detect a collision.

In order to get the best results these graphics should cropped as closely to the image that is to be displayed as possible. Below is an example of two images that could be used in the game. Both will display exactly the same way because the space around the plane is transparent. However the top image is more optimized for the collision detection system though because it is closely cropped to the actual image of the plane. The bottom image would appear to collide with other objects before it should because the collision detection system doesn't take any notice of the transparent border, and assumes that the entire area of the image will be used as the collision area.

So lets take a look at the changes that are needed in the GameObject class to implement collision detection.

Showing page 1 of 6
1
234
...
6
next
Subscribe to Web Development
RSS
Get free weekly updates, directly to your inbox.
Browse Web Development