我需要一系列背景?

时间:2011-10-07 05:23:54

标签: java swing side-scroller

在我的横向卷轴中,我希望有3个背景可以保持循环。每当你通过一个阶段时,它会调用函数nextStage(),它将你带到下一个背景。在课堂上:

package com.erikbalen.game.rpg;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class World extends JPanel implements ActionListener{

/**
 * 
 */
private static final long serialVersionUID = 2834816426699432121L;
Player p1;
Image background;
Timer time;

public World() {
    p1 = new Dps();
    addKeyListener(new AL());
    setFocusable(true);
    ImageIcon icon = new ImageIcon("C:\\Program Files (x86)\\EriksRPG\\Images\\Backgrounds\\background.png");
    background = icon.getImage();
    time = new Timer(5, this);
    time.start();
}

public void actionPerformed(ActionEvent e) {
    p1.move();
    repaint();
}

public void paint(Graphics g) {
    super.paint(g);
    Graphics g2d = (Graphics2D) g;

    g2d.drawImage(background, 0, 0, null);
    g2d.drawImage(p1.getImage(), p1.getX(), p1.getY(), null);

}

private class AL extends KeyAdapter {
    public void keyReleased(KeyEvent e) {
        p1.keyReleased(e);
    }

    public void keyPressed(KeyEvent e) {
        p1.keyPressed(e);
    }       
    }       
}

基本上我想知道如何创建一个称为背景的图像数组,加载这三个文件,并创建一个名为next loads background[stage] and if stage > 2 stage = 0

的nextStage()方法

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案:

使“背景”成为3个元素的数组

Image[] background = new Image[3];

将三个背景图像一次加载到背景[0],背景[1]和背景[2]中。

创建一个新的私有变量,可能称为stage,并在前进时递增:

private int stage = 0;

public void nextStage() { stage++; }

最后,在paint()中,根据stage:

的值绘制所需的背景
g2d.drawImage(background[stage % 3], 0, 0, null);