GAMES TWO: LESSON FOUR: Collision Detection: Stationary Objects
In this lesson we will use a technique to determine when one moving polygon
has collided with a stationary polygon. Make sure you play around with the
same applet before reading the discussion of how it works. In this applet
you use the four arrow keys to change the speed and altitude of the
airplane.
The code for this applet is contained in three separate files:
- FLY1.java
- Tools2D.java
- Point2D.java
The main applet class is defined in FLY1.java. The other two classes,
Tools2D and Point2D, are used in FLY1.java to determine when a collision
between the plane and the mountain occur. Study these lines from early in
FLY1.java:
int x_mtn[]={ 0,0,25,80,85,90,150,175,200,225,265,290,305,
340,360,415,425,435,500,500,0};
int y_mtn[]={ 300,260,240,165,160,165,250,282,282,250,125,
120,125,250,250,170,178,170,280,300,300};
Point2D mountain[] = new Point2D[21];
public void init(){
d = getSize();
for(int i = 0; i
As you can see, the mountains are defined as two int arrays (one for the x
points and one for the y points). These two int arrays are used later in the
draw method to actually draw the mountains. The only purpose of the array of
Point2D is to determine when a collision has occured. You will notice that
the values stored in the two int arrays (x_mtn and y_mtn) are copied into
the array of Point2D called mountain.
Collision detection is carried out during every cycle of the run method
through a call to the collision method:
public boolean collision(){
if(Tools2D.insidePolygon(new Point2D(x_plane_body[0],y_plane_body[0]), mountain))
return true;
else if(Tools2D.insidePolygon(new Point2D(x_plane_body[1],y_plane_body[1]), mountain))
return true;
else return false;
}
The collision method makes calls to Tools2D.insidePolygon to determine if
the nose of the plane (x_plane_body[0],y_plane_body[0]) or the tip of the
wing of the plane (x_plane_body[1],y_plane_body[1]) are within the
boundaries of the mountain. Only these two points need to be checked due to
limitations on the directions in which the plane can move.
Here is the code to Tools2D.insidePolygon:
static boolean insidePolygon(Point2D P, Point2D[] pol){
int n = pol.length, j = n - 1;
boolean b = false;
float x = P.x, y = P.y;
for(int i = 0; i 0 ||
pol[i].y <= y && y < pol[j].y &&
Tools2D.area2(pol[j], pol[i], P) > 0 ) b = !b;
j = i;
}
return b;
}
For the purposes of this assignment, just make sure that you know how to use
the insidePolygon method of Tools2D and that you know how to constuct a new
instance of Point2D.
If it is determined that the plane is within the boundaries of the mountain
polygon then the location of the plane is reset and the crashes variable is
incremented.
ASSIGNMENT: