Adam Brodin
Adam Brodin

Reputation: 71

Libgdx multiple enemies

I am creating a game where a player has to dodge enemies, now that works fine with one enemy. But how do i create like an array of enemies to spawn them constantly? Here is the class/object i want to create multiple objects of:

public class Spike extends MoveEntity 
{
    public Spike(float speed, float rotation, float width, float height,    Vector2 position) 
    {
        super(speed, rotation, width, height, position);
    }

    void move(float delta) 
    {

    }

    public void update() 
    {
        position.y -= 3;
    }

}

And here is how I render it (just one enemy):

sb.draw(sp_bg5, s.getPosition().x, s.getPosition().y, s.getWidth() / 2, s.getHeight() / 2, s.getWidth(), s.getHeight(), 1, 1, 0);

Thank you for any help! :)

Upvotes: 0

Views: 778

Answers (1)

Vincent
Vincent

Reputation: 484

I think what you are looking for is a list (specifically, a java.util.LinkedList). You can create one like this:

LinkedList<Spike> enemies = new LinkedList<Spike>();

and add enemies in like this:

enemies.add(new Spike(speed, rotation, width, height, position);

and finally draw them like this:

for (Spike s : enemies) {
    sb.draw(sp_bg5, s.getPosition().x, s.getPosition().y, s.getWidth() / 2, s.getHeight() / 2, s.getWidth(), s.getHeight(), 1, 1, 0);
}

It will get more complicated if you want to de-spawn them, however. Java won't let you modify a list normally while you're iterating through it. You will have to use a special iterator for this:

ListIterator<Spike> it = enemies.listIterator();
while (it.hasNext()) {
    Spike s = it.next();
    if (s.shouldBeRemoved()) {
        it.remove();
    }
}

and you could of course replace shouldBeRemoved with whatever check is necessary.

Upvotes: 1

Related Questions