如何在边界之间反弹图像

时间:2016-06-05 04:03:29

标签: java image applet

我试图在我的窗口边界之间反弹球图像。然而,当球到达顶部边界时,它不会反弹。我希望有些人可以帮我解决这个问题。

这是我的代码:

    import java.awt.*;
    import java.applet.*;
    public class Ball {
    private int x=355 ;
    private int y=500;
    private int xVel = -3;
    private int yVel = 3;

    private Image ball;

    public Ball (Breakout bR){

        ball = bR.getImage(bR.getDocumentBase(),"ball.png");


    }
    public void update(Breakout bR){
       x += xVel;
       y += yVel;
       if (x < 0){
           xVel = 3;
        }
       else if (x > bR.getWidth()){
            xVel = -3;
        }
       if(y > bR.getHeight()){
           yVel = -3;
        }
       else if (y < 0){
            xVel = 3;
        }
    }

    public void paint (Graphics g, Breakout bR){
        g.drawImage(ball,x,y,bR);

    }
}

Thanks for your help :)   

1 个答案:

答案 0 :(得分:3)

你的最后一个错误 - 如果......应该读

   else if (y < 0){
        yVel = 3;
    }