In my side-scroller, I want to have 3 backgrounds that keep looping. Whenever you get through a stage it calls the function nextStage() that sends you to the next background. In the class:
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);
}
}
}
Basically I want to know how I can make an array of images called backgrounds, load those three files, and make a method called nextStage() that loads background[stage] and if stage > 2 stage = 0
one possible solution:
make "background" an array of 3 elements
load the three background images one at a time into background[0], background[1] and background[2].
create a new private variable, perhaps called stage, and increment when advancing:
finally, in paint(), draw the background you want, according to the value of stage: