Invaders Improved

As you'll recall, we ran into a problem during the first lab session on October 23, trying to move from the first version of our Space Invaders project, where ten invaders are present on the stage at the start of the action, to a more flexible version where the cast is generated by performing the attachMovie() method a random number of times. We could get the invaders to appear, but they were not vulnerable to our bullets.

Here's the solution, arrived at with help from Roni Noone. The invaders appeared to dodge our bullets because of a subtle problem in the hit testing expression. You'll remember that we decided to test each invader for collision with any of the bullet objects, thus:

this.hitTest(_root.bullet)

You'll remember that this always refers to the object to which the code is attached. In old-style Flash design, where we manually assign instance names to Movie Clips, there is no chance of ambiguity. This always translates as the name of the Movie Clip to which the code belongs.

But when a Movie Clip is generated through attachment, it acquires its instance name from the attachMovie() statement.

You'll remember that we added code to the root level of the main movie, generating copies of the invader Movie Clip by an iterative for loop. Within the loop, we'd originally written:

_root.attachMovie('invader','invader',
_root.getNextHighestDepth())

This statement creates a population of invaders each of which has the instance name invader. That is, they all have the same name.

Such generality is allowable, but it does not allow proper hit testing. When each invader performs its testing code, it supplies a value for this which is not unique.

Here's a successful substitute:

for(i=0; i<5+Math.floor(Math.random()*10); i++)
{
    _root.attachMovie('invader','invader'+i, 
    _root.getNextHighestDepth());
}

What's different? We use the loop's counter or index variable, i, as part of the instance name of each generated invader clip. So the first is invader0, the second is invader1, and so forth.

We don't have to change anything in the class code, however: the hit test continues to work as usual, only this time each invader is properly tested because the keyword this is properly resolved.

Source files

The source file for the improved project, invaderDemoImproved.fla, is available on student-iat.ubalt.edu within the idia610Shared folder, in Lab05.


University of Baltimore Logo

Copyright © 2004 School of Information Arts and Technologies