O'Reilly logo

Killer Game Programming in Java by Andrew Davison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Obstacles

The Obstacles class creates a series of blue cylinders placed at random locations around the XZ plane. The cylinders have a fixed radius, but their heights can vary between 0 and MAX_HEIGHT (8.0f). A cylinder is positioned with a TransformGroup and then added to a BranchGroup for all the cylinders; the BranchGroup is then retrieved by calling getObsBG().

At the same time that a cylinder is being created, a BoundingBox is calculated:

    height = (float)(Math.random()*MAX_HEIGHT);
    lower = new Point3d( x-RADIUS, 0.0f, z-RADIUS );
    upper = new Point3d( x+RADIUS, height, z+RADIUS );
    bb = new BoundingBox(lower, upper);

A boid checks an obstacle's bounding box to avoid colliding with it. The bounding boxes for all the obstacles are added to an ArrayList, which is examined by boids when they call isOverLapping(). A boid calls isOverLapping() with a BoundingSphere object representing its current position:

    public boolean isOverlapping(BoundingSphere bs)
    // Does bs overlap any of the BoundingBox obstacles?
    { BoundingBox bb;
      for (int i=0; i < obsList.size(); i++) {
        bb = (BoundingBox)obsList.get(i);
        if( bb.intersect(bs) )
          return true;
      }
      return false;
    } // end of isOverlapping()

The isOverlapping() method sacrifices efficiency for simplicity: the bounding sphere is checked against every obstacle's bounding box in the scene. An obvious improvement would be to order the bounding boxes in some way to reduce the number that needs to be tested. However, this would complicate the code and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required