## Question of the Week

Predicting Collisions - Page 5
by kirupa  |  23 October 2005

In the previous page, I started explaining the code. Let's pick up where we left of with the moveAway code.

count = 0;
this.createEmptyMovieClip("temp", 1000);

In the first line, a variable count is initialized with a value of zero. In the second line, I am creating an empty movie clip called temp that will be used to store event handlers. The empty movie clip will be created at a depth of 1000.

temp.onEnterFrame = function() {

I quickly put our temp movie clip we created earlier to good use! I set our temp movie clip to hold an onEnterFrame event handler that executes any code contained in it as fast as our frame rate.

count++;
if (count == 5) {
delete temp.onEnterFrame;
}

In our onEnterFrame function, I first increment the value of count by one. If our count variable increments to a value of 5, I decide to kill our onEnterFrame function by deleting it.

for (i=0; i<final_targets.length; i++) {
tempA = eval(final_targets[i]);
// horizontal movement
if (diffX>diffY) {
if (tempA._y>circleMain._y) {
tempA._y += 10;
} else {
tempA._y -= 10;
}
} else {
// vertical movement
if (tempA._x>circleMain._x) {
tempA._x += 10;
} else {
tempA._x -= 10;
}
}
}

This code seems complicated, but it is really straightforward. What I am doing is going through each target movie clip that is in the way of our path circles and moving them out of the way. Our final_targets array stores the instance names of every movie clip that collided with our path circles, so knowing which circles to move has already been done for us.

With a for loop, I am able to loop through each movie clip referenced in our final_targets array and move them out of the way. I deliberately planned how I want to move the circle out of the way. If you remember, very early in my code explanation, I mentioned the diffX and diffY variables.

What both the diffX and diffY variables do is store the horizontal distance and the vertical distance needed for our mainCircle movie clip to travel to reach the final destination. If diffX is larger, that means you are moving further horizontally than vertically. The opposite is true if our diffY variable is greater - your mainCircle moves more vertically as opposed to horizontally.

Once I determine in which direction our mainCircle movie clip predominantly moves in, I can adjust how I want our target circles to move to avoid the collision. If there is a collision, it is easier to move our target circles perpendicularly away from the direction of our mainCircle's movement. In short, that is all our above code does.

If our circle is moving more horizontally, I move our target movie clips vertically. Of course, if our circle is moving vertically, I move our target movie clips horizontally.

Onwards to the next page!

 page 5 of 6