I am making a bounc*ing cube that moves around a frame. To detect the boundary of the frame, I used getHeight() and getWidth() from the JComponent in the JFrame and calculate the possible boundary so that the cube can rebound.
It works totally fine for getWidth(). However, I cannot make it rebound on the boundary for getHeight().
When the cu*be goes to the top of the window, it keeps going for about 10 pixels before rebounding.
Here is the screenshot for this problem.
Here is my code:
public class Cube {
final public static int DIMENSION = 100;
private final static int D_X = 20;
private final static int D_Y = -20;
private final static int SPEED = 1;
private int xVelBK;
private int yVelBK;
private int xVel;
private int yVel;
private CubePoint[] pts;
public Cube(int x, int y){
xVel = SPEED;
yVel = SPEED;
pts = new CubePoint[8];
pts[0] = new CubePoint(x,y);
pts[1] = new CubePoint(x,y - DIMENSION);
pts[2] = new CubePoint(x + DIMENSION,y - DIMENSION);
pts[3] = new CubePoint(x + DIMENSION,y);
pts[4] = new CubePoint(x + D_X,y + D_Y);
pts[5] = new CubePoint(x + D_X,y + D_Y - DIMENSION);
pts[6] = new CubePoint(x + D_X + DIMENSION,y + D_Y - DIMENSION);
pts[7] = new CubePoint(x + D_X + DIMENSION,y + D_Y);
}
public void move(int componentWidth, int componentHeight){
......
//bug in here
if (pts[0].getY() - DIMENSION - D_Y <= 0 ) {
yVel = SPEED;
}
.......
}
..........
}
Here is the component :
public class CubeComponent extends JComponent {
...........
private Cube cube;
private Timer timer;
private CubePoint originMousePos;
private CubePoint closest;
private Font font;
private int mode;
private int delay = DEFAULT_DELAY ;
private int mouseToClosestX;
private int mouseToClosestY;
class CubeMoveListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
cube.move(getWidth(),getHeight());
repaint();
}
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
cube.draw(g2);
}
}
As far as I can tell:
if (pts[0].getY() - DIMENSION - D_Y <= 0 ) {
SHOULD be used to determine when the cube reaches the bottom of the component so you should be testing for ">"
and
if ( pts[0].getY() >= componentHeight) {
SHOULD be used for testing when the cube reaches the top. So it should be:
if ( pts[0].getY() <= 0) {
The key point is that: