Monday, June 29, 2009

Java Greenfoot: Wombats Collision

Here we consider the wombats or wombats2 scenario included in the standard Greenfoot distribution. The last modification mentioned in the tutorial made by Michael at the Greenfoot site, is to "stop wombats from walking through rocks". This is done by adding the following codes
List rocks = myWorld.getObjectsAt(x, y, Rock.class);  
if(rocks.isEmpty()) { return true; } else { return false; }

which replace the last statement in the canMove() method. With such a modification, a wombat "sees" first before it moves. But, it recognizes only rocks and the borders of the world. We can extend this functionality, by giving a capability to "see" other wombats and then perform an appropriate action. For example, if it is facing other wombat objects it changes its moving direction. To implement this, replace the codes above with the following snippet.
List rocks = myWorld.getObjectsAt(x, y, Rock.class);  
if(!rocks.isEmpty()) { return false; }

List otherwombats = myWorld.getObjectsAt(
x, y, Wombat.class);
if(otherwombats.isEmpty()) { return true; }
else { return false; }

The following picture illustrates the result of this modification.


Wombats behavior after modification; shown by sequential calling of method act()


As you can see, a wombat detects first whether rocks exist in the cell in front of it. If the result is negative, it tries to detect if there are other wombats. When it indeed meets ones, canMove() will return false i.e. it can not move forward, otherwise it can.

Webpage Keywords : Java programming, Java game, Greenfoot scenario

No comments:

Post a Comment