如何从左到右移动背景图像?

时间:2016-03-12 22:43:12

标签: java

我正在使用Java制作游戏,我希望背景图像从右向左移动。我想继续重复这样看起来就像玩家正在移动。

我在下面编写代码来执行此操作,但是它存在问题。图像将从右向左移动两次,但第三张图像不会出现。任何想法?

public void update() {
    x -= dx;
}

public void draw(Graphics2D g) {

    // 1st image
    g.drawImage(image, (int) x, (int) y, GamePanel.WINDOW_WIDTH, GamePanel.WINDOW_HEIGHT, null);

    // keep scrolling the image
    // there will be two same bg image on screen
    if (x < 0) {
        g.drawImage(image, (int) x + GamePanel.WINDOW_WIDTH, (int) y, GamePanel.WINDOW_WIDTH, GamePanel.WINDOW_HEIGHT, null);
    }
    if (x > 0) {
        g.drawImage(image, (int) x - GamePanel.WINDOW_WIDTH, (int) y, GamePanel.WINDOW_WIDTH, GamePanel.WINDOW_HEIGHT, null);
    }
}// End of draw method

看起来x的值永远保持在十进制,所以我添加了这段代码,但仍有一部分缺少图像:

if(x+GamePanel.WINDOW_WIDTH < 0){
            x = GamePanel.WINDOW_WIDTH;
        }

1 个答案:

答案 0 :(得分:1)

很简单。只需将两个图像放在一起,不要忘记在某个时刻重置x。

由于每张图像都与窗口一样宽,因此首先您只能看到第一张图像。然后它向左滚动,另一个图像从右侧滑入。滚动太多以至于只有第二张图像可见后,您可以切换回开头。 (我假设它是一个简单的平台滚动器,两个图像完全相同。)

|11111|
|11112|
|11122|
|11222|
|12222|
|11111| as above

在代码中:

public void update() {
    x -= dx;
    if (x<-GamePanel.WINDOW_WIDTH) {
        x+=GamePanel.WINDOW_WIDTH; 
        // or reset to zero
    }
}

public void draw(Graphics2D g) {

    // 1st image
    g.drawImage(image, (int) x, (int) y, GamePanel.WINDOW_WIDTH, GamePanel.WINDOW_HEIGHT, null);

    // 2nd image right to 1st image
    g.drawImage(image, (int) x + GamePanel.WINDOW_WIDTH, (int) y, GamePanel.WINDOW_WIDTH, GamePanel.WINDOW_HEIGHT, null);

}// End of draw method
相关问题