GAMES TWO: LESSON FOUR: Collision Detection: Moving Objects

In this lesson, collision detection is complicated a bit by the presence of a moving object. Not only can the plane crash into the mountains, but it can also crash into the balloon. Spend a few moments experimenting with the behavior of the sample applet before reading on.

The code for this applet is contained in three separate files:

  1. FLY2.java
  2. Tools2D.java
  3. Point2D.java
The Tools2D and Point2D classes are the same as those used in the last lesson and so we won't really inspect them in this lesson (although you may need to review them before proceding with this lesson).

To keep track of the location of the balloon the following data structures were added to the applet:

int x_ball[] = {400,406,409,413,418,420,418,413,409,406, 400,394,391,387,382,380,382,387,391,394,400}; int y_ball[] = { 10, 12, 16, 21, 25, 30, 35, 39, 43, 46, 50, 46, 43, 39, 35, 30, 25, 21, 16, 12, 10}; int x_basket[] = {380, 400, 420, 405, 395, 380}; int y_basket[] = { 65, 65, 65, 77, 77, 65}; int x_reset_ball[] = {400,406,409,413,418,420,418,413,409,406, 400,394,391,387,382,380,382,387,391,394,400}; int y_reset_ball[] = { 10, 12, 16, 21, 25, 30, 35, 39, 43, 46, 50, 46, 43, 39, 35, 30, 25, 21, 16, 12, 10}; int x_reset_basket[] = {380, 400, 420, 405, 395, 380}; int y_reset_basket[] = { 65, 65, 65, 77, 77, 65}; Point2D balloon[] = new Point2D[6];
For purposes of collision detection it was not necessary to contain all the points in the arrays for the basket and the ball. Instead a subset of these points was selected. This has a speed advantage since fewer points are used in the collision detection algorithm this way.
public void setBalloonPts(){ balloon[0] = new Point2D(x_ball[0],y_ball[0]); balloon[1] = new Point2D(x_ball[5],y_ball[5]); balloon[2] = new Point2D(x_basket[3],y_basket[3]); balloon[3] = new Point2D(x_basket[4],y_basket[4]); balloon[4] = new Point2D(x_ball[15],y_ball[15]); balloon[5] = new Point2D(x_ball[0],y_ball[0]); }
The setBalloonPts method is called from collision method since each these points must be constantly reset in order to detect a collision between the balloon and the plane. The values for the mountains are static and so it is not necessary to constantly reset the values for the mountains.

The balloon moves both vertically and horizontally and this movement is completely accounted for from within the run method:

if(x_ball[5]<0){ for(int i = 0; i< x_basket.length; i++){ x_basket[i] +=d.width; } for(int i = 0; i<x_ball.length; i++){ x_ball[i] +=d.width; } } for(int i = 0; i< y_basket.length; i++){ y_basket[i] += DIR; } for(int i = 0; i<y_ball.length; i++){ y_ball[i] += DIR; } if(collision()) reset(); if(y_ball[0]<3) DIR=1; else if(y_ball[0]>54) DIR=-1;
Finally, drawing the balloon requires drawing two separate polygons plus three lines. You can easily find this code within the draw method.


ASSIGNMENT: