Step 3: Collision detection
We now have one key thing to do to turn this into a game. We need to add in collision detection.
We want to detect when a laser hits an enemy spaceship and consequently make the spaceship explode and disappear. Similarly we want to detect when an enemy spaceship collides with the players spaceship, at which point the game will end.
So how do we detect collisions in flash?
The spaceship, enemies and lasers are all movieclips. So we need a simple way to detect collisions between movieclips.
The answer is hitTest. Flash 5 introduced a method called hitTest which allows us to detect collisions between two movie clips and its really easy to use.
If you have two movieclips with instance names movie1 and movie2 then the code to detect a collision would be movie1.hitTest(movie2).
A few words about hitTest
There are actually two different ways you can use hitTest.
Usage 1: You can use it to detect the collision (or overlap) between two movie clips using the syntax: movie1.hitTest(movie2) This will be true if the bounding boxes of the two movieclips are overlapping.
So what's a bounding box? Think of it as an invisible rectangle drawn around the edge of a movie clip. If you click on a movie clip in flash you will see the bounding box highlighted (see right). hitTest detects when the bounding boxes of two movie clips overlap, not when the graphics overlap.
The image to the left shows the bounding boxes for the spaceship and the enemy. The two bounding boxes are overlapping so if we used hitTest to check for a collision it would be true even though the actual graphics don't overlap.
This isn't really a problem because the spaceship graphics mostly fill the bounding box and because the game moves so fast that players are unlikely to notice this lack of precision.
Usage 2: You can use it to detect a collision between a movie clip and a point. The syntax is movie1.hitTest(x, y, shapeFlag) where x and y are the co-ordinates of the point and shapeFlag is either true or false depending of whether you want to detect a collision between the movie clips graphic (true) or the movie clips bounding box (false). This usage of hitTest can give you a more precise collision detection but its not used much in games because we generally want to detect the collision between two movie clips not a point and a movie clip.
|» Level Intermediate|
Rating: 9 Votes: 517
|No details available.|
|Download the files used in this tutorial.|
|Download (416 kb)|
|More help? Search our boards for quick answers!|