The Every so often, the fish should change direction, just as fish in an aquarium might. Here's how that works in the 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); velocity.y = Math.max(velocity.y, -8); } . . . Next, the code adds the x and y components of the fish's velocity to move the fish to a new position: location.x += velocity.x; location.y += velocity.y; All that's left to do is to determine if updating the fish's position has put it beyond the edge of the aquarium, in which case the fish should bounce off the edge of the tank, which you can make happen by reversing the sign of its x or y velocity, like this: if (location.x < edges.x) { location.x = edges.x; velocity.x = -velocity.x; } if ((location.x + image1.getWidth(tank)) > (edges.x + edges.width)){ location.x = edges.x + edges.width - image1.getWidth(tank); velocity.x = -velocity.x; } if (location.y < edges.y){ location.y = edges.y; velocity.y = -velocity.y; } if ((location.y + image1.getHeight(tank)) > (edges.y + edges.height)){ location.y = edges.y + edges.height - image1.getHeight(tank); velocity.y = -velocity.y; } } That completes the |

Java After Hours: 10 Projects Youll Never Do at Work

ISBN: 0672327473

EAN: 2147483647

EAN: 2147483647

Year: 2006

Pages: 128

Pages: 128

Authors: Steven Holzner

Similar book on Amazon

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net