0

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

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Erik Balen
  • 275
  • 1
  • 4
  • 11

1 Answers1

1

one possible solution:

make "background" an array of 3 elements

Image[] background = new Image[3];

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:

private int stage = 0;

public void nextStage() { stage++; }

finally, in paint(), draw the background you want, according to the value of stage:

g2d.drawImage(background[stage % 3], 0, 0, null);
Ben
  • 719
  • 6
  • 25
  • Thanks a LOT! I ran into a little kink but I fixed it because I made nextStage a static method so I could access it from inside the player class. – Erik Balen Oct 07 '11 at 06:14
  • unrelated to the problem, but you might consider giving the player a member variable which stores the game object (pass it along in the constructor). you're probably not going to have multiple stages going at once, so it doesn't really matter in this case, but in general, the practice of "make it static to increase its visibility" will likely cause you problems (ex: if you gave players a Shield variable, and made it static so that enemies could access it, and then later made it a two-player game, you'd find that the two players share the same shield, instead of each having their own!) – Ben Oct 07 '11 at 06:27