Search code examples
javaeclipseslick2d

How to create two of the same objects but in different states


I am trying to create at least two independent objects using the same class. Meaning that I want each of them to use the same class but use the variables in it independently. I am not sure if this is possible but that is why I am here.

The two skeletons (skeleton1 and skeleton2) are the two objects that I want to be independent of each other.

@Override
public void render(GameContainer gc, StateBasedGame gm, Graphics g)
        throws SlickException {

    background.draw(0, 0, Constants.WIN_WIDTH, Constants.WIN_HEIGHT);

    g.drawImage(ccb, mkX, mkY);

    Skeleton skeleton1 = new Skeleton(g, gm);
    Skeleton skeleton2 = new Skeleton(g, gm);

    score = new DeathScreenButton(scoreCounter, (Constants.WIN_WIDTH / 2) / 2, 0, g, Color.transparent);

}

More specifically, I want their x and y axis to be independent shown here (they are sX and sY):

public class Skeleton {

private Graphics g;
private StateBasedGame gm;

private int mkX = InGame.getmkX();
private int mkY = InGame.getmkY();

// This makes them spawn on each other :(
// "static" prevents them from popping around the screen
private static int sX = (int)(Math.random() * Constants.WIN_WIDTH) + 1;
private static int sY = (int)(Math.random() * Constants.WIN_HEIGHT) + 1;

private Image skele;

public Skeleton (Graphics g, StateBasedGame gm) {

    this.g = g;
    this.gm = gm;

    try {
        init();
    } catch (SlickException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    render();

    try {
        update();
    } catch (SlickException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Solution

  • Your Skeletons are independent already. One of Objected-Oriented programming purposes are class instances. This way, two instances of the same class may have the same attributes, but they will never be the same. It may be a little confusing in the beginning, but the objective is to develop reusable code, then you may instantiate 1..n Skeletons, and they will be independent.

    Skeleton skel1 = new Skeleton(Graphics g, StateBasedGame gm);
    

    Hope it was helpful. Thank you.