0
\$\begingroup\$

I'm trying to create a little 2D-Zombie-Shoot game. I'm pretty much at the beginning of programming. At least, I can create a player that is moving with arrow keys and stuff. My question is: How do I spawn a Zombie on a button-press? I've already tried it, but with no good results. Here's the code:

//A variable, for the amount of zombies spawned
public int zombie = 0;


 public void tick() {
 //The rest of the code is irrelevant
 ...........

    if (mouse1.isPressed()) {
        zombie++;
    }

}

public void render() {
    //The rest of the code is irrelevant
    ...........

    //Player
    g.drawImage(playerImage, x, y, null);

    //Check how many zombies should be created
    if (zombie > 0) {
        g.drawImage(zombieImage, zX, zY, null);
    }
    ...........
\$\endgroup\$
  • 3
    \$\begingroup\$ With your current code you'll only ever see one zombie. You need a separate 'x' and 'y' value for each in order to draw them in different locations. \$\endgroup\$ – Alex May 4 '15 at 20:21
1
\$\begingroup\$

You will need a zombie class.

public class Zombie {
public int x, y;

public Entity(int x, int y) {
    this.x = x;
    this.y = y;
}

public void tick() {
//code to control movement and such
    }

public void render() {
    g.drawImage(zombieImage, x, y, null);
}
}

I'm not sure which class you are showing in your code but you will need to make a zombie ArrayList for your zombies in it.

protected List<Zombie> zombies = new ArrayList<Zombie>();

In your tick method you should call all of the zombie's tick methods like this

for (int i = 0; i < zombies.size(); i++) {
            zombies.get(i).tick();
        }

You also need a similar thing in render

for (int i = 0; i < zombies.size(); i++) {
            zombies.get(i).render();
        }

This will allow you to have multiple zombies, in order to add new zombies, you call zombies.add(new Zombie(your x value you want, your y value you want);

In order to remove zombies you call zombies.remove(the index of the zombie to remove);

If you just do this, you will need to know to know the index of the zombie to remove. To get around this you could have a boolean called removed inside of the Zombie class. You can then cycle through the ArrayList as earlier and simply remove the zombies that have the removed variable equal to true like this

for (int i = 0; i < zombies.size(); i++) {
            if (zombies.get(i).removed) zombies.remove(i);
        }

This will allow you to have multiple zombies and have them all render and update simultaneously.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.