矩形坐标不更新

Rectangle Coordinates Not Updating

我正在尝试让基本交叉点与我正在开发的游戏一起使用,因此我需要定义它们的碰撞箱。但是,当使用 g2d.draw(rectangle) 时,矩形不会相对于其更新的坐标移动。

int x = 100 ;
int y = 100 ;
int x2 = x + 100;
int y2 = y + 100;

Rectangle hitbox = new Rectangle(x,y,x2,y2) ;

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    //Graphical loop start
    g2d.draw(hitbox) ;
    repaint() ;
    //Graphical loop end
    }

带有 keylistener 组件的 gameloop

public void run() {

    while(running) {

        //Player movement
        if (left) {
            if (x <= -225) {
                x = 1440 ;
            }
            x = x - 2 ;
        }
        if (up) {
            if(y <= -225) {
                y = 900 ;
            }
            y = y - 2 ;
        }
        if (right) {
            if (x >= 1416) {
                x = -24 ;
            }
            x = x + 2;
        }
        if (down) {
            if (y >= 900) {
                y = -10 ;
            }
            y = y + 2 ;
        }
        //Player movement

        //ball movement
        if (cubey > y) {
            cubey-- ;
        }
        if(cubey < y) {
            cubey++ ;
        }
        if (cubex > x) {
            cubex-- ;
        }
        if (cubex < x) {
            cubex++ ;
        }

根据提供的代码,碰撞框矩形和您更改的坐标之间没有联系。使用新的 x,y 更新矩形,然后重新绘制。

像这样:

public void run() {
    while(running) {
       //...
       hitbox.setBounds(x,y,100,100);
    }
}

即使您的程序流程应该如何工作也没有效率。