为什么我的 move() 方法不能将球保持在界内



问:所以我创建了一个带有 Window 类的程序,该程序创建了一个 JFrame 并将我的 DrawStuff 类中的 JPanel 添加到其中。DrawStuff 类创建一个球,该球(应该)在屏幕上弹跳,当它击中 JFrame 边界时,改变方向。球移动,但由于某种原因,我的移动方法的检查边界部分不起作用。任何帮助将不胜感激。我的目标是把球保持在界内。

来自 DrawStuff 类的代码

public class Drawstuff extends JPanel {
    private int x = 0;
    private int y = 0;
    private int dx, dy=0;
    public  Drawstuff(){
        x = 300;
        y = 250;
        dx = 0;
        dy = 0;
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        this.setBackground(Color.BLACK);
        g2d.setColor(Color.RED);
        g2d.fillOval(x,y,50,50);    
    }
    public void move(){
        if (x < 600){
            dx = 1;
        }
        if (y < 500){
            dy = 1; 
        }
        if (x > 600){
            dx = -1; 
        }
        if (y >500){
            dy = -1;
        }
        x += dx;
        y += dy;
    }
}

来自窗口类的简单"游戏循环"(如果需要)

 while (true){
            stuff.repaint();
            stuff.move();
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

你的move错了。它的逻辑是错误的。您希望球反弹,因此当它撞到墙壁时使其运动相反。你所做的是:如果它在外面,把它弄进去,当它在里面时,试着把它放在外面!更改为:

   public void move(){
        if (x < 0) { // left bound
            dx = 1;  // now move right
        }
        if (y < 0){  // upper bound
            dy = 1;  // now move down
        }
        if (x > 600){// right bound
            dx = -1; // now move left
        }
        if (y >500){ // lower bound
            dy = -1; // now move up
        }
        x += dx;
        y += dy;
    }

为了将来使用,我可以建议您通过以下方式进行操作:

   public void move(){
        if (x < 0) {   // left bound
            dx = -dx;  // now move right, same speed
            x=-x;      // bounce inside
        }
        if (y < 0){    // upper bound
            dy = -dy;  // now move down, same speed
            y=-y;      // bounce inside
        }
        if (x > 600){      // right bound
            dx = -dy;      // now move left, same speed
            x=600-(x-600); // bounce inside
        }
        if (y >500){       // lower bound
            dy = -dy;      // now move up, same speed
            y=500-(y-500); // bounce inside
        }
        x += dx;
        y += dy;
    }

因此,您现在可以使用所需的任何矢量速度(至少是合理的矢量速度)。矢量坐标根据击球反转,球在边界内重新定位。

相关内容

最新更新