In last example, we can see two rectangles moving on the screen. But these two rectangles will go outside the boundry eventually. We add a method here to check if this object hit the boundry. When it hits the boundry, we change the object's moving direction. Now, you can see two rectangle bouncing inside the boundry.
We add a boundry check mothod in mPoint as follow:
public void checkBoundry(Rectangle rect) { int nx = x+dx; /* caculate new location */ int ny = y+dy; /* check if new location out of boundry */ if ( (nx= rect.x+rect.width) ) dx = -dx; if ( (ny = rect.y+rect.height) ) dy = -dy; }
The boundry check in mRectangle is slightly different. So we redefine the checkBoundry in mRectangle.
public void checkBoundry(Rectangle rect) { /* overwrite the mPoint's checkBoundry */ /* the rectangle's checkBoundry is different */ int nx = x+dx; int ny = y+dy; if ( (nx= rect.x+rect.width) ) dx = -dx; if ( (ny = rect.y+rect.height) ) dy = -dy; }
Class Hierarchy: Applet --- Test mPoint --- mRectangle
JAVA Source Code
1. Test.java (Main Program)
1. mPoint.java (Movable Point)
1. mRectangle.java (Movable Rectangle)