June 2005
Beginner to intermediate
336 pages
6h 29m
English
The swim method is what gets those fish to go. It does this by incrementing the location x and y coordinates by adding the x and y values stored in the velocity variable each time swim is called.
Every so often, the fish should change direction, just as fish in an aquarium might. Here's how that works in the swim method, which, every now and then, adds new random numbers to the x and y component of the velocity and then makes sure no velocity component exceeds an absolute magnitude of 8:
public void swim()
{
if(random.nextInt() % 7 <= 1){
velocity.x += random.nextInt() % 4;
velocity.x = Math.min(velocity.x, 8);
velocity.x = Math.max(velocity.x, -8);
velocity.y += random.nextInt() % 4;
velocity.y = Math.min(velocity.y, 8); ...Read now
Unlock full access