Thursday, 26 September 2013

Java Game - how to add enemies using Arraylist?

Java Game - how to add enemies using Arraylist?

I'm doing my first Java game using GdxLib, and i want to create enemies
using an ArrayList (but im not sure of how to do it), and that all of them
spawn in a random position, but i got few problems,
Im creating them wrong cause they are spawning like a 'line' because i
dont know how to spawn them randomly.
When any of my created enemies on Screen 'dies' (count == 20) if i shoot
any other enemy i can't kill it.
Here is the class code:
public class World {
gameMain game;
Ship ship;
ArrayList<Bullet> bullets = new ArrayList<Bullet>();
ArrayList<Follower> enemies = new ArrayList<Follower>(5);
WorldRenderer wr;
Iterator<Bullet> bIter;
Iterator<Follower> eIter;
Bullet b;
Enemy e;
int count = 0;
int shipCount = 0;
float x = 0;
float y = 0;
public World (gameMain game){
this.game = game;
ship = new Ship(new Vector2(20, 15), 1, 1, 0, 5f);//Ship Atributes
for (int i= 0;i<5; i++){ Creates 5 enemies
enemies.add(new Follower(5f, 0, 1, 1, new Vector2(x,y)));
x = x+2;
y = y+2;
}
Gdx.input.setInputProcessor(new InputHandler(this));
}
public Ship getShip(){
return ship;
}
public ArrayList<Follower> getEnemies(){
return enemies;
}
public void update(){
ship.update();
bIter = bullets.iterator();
while(bIter.hasNext()){
b = bIter.next();
b.update(ship);
}
eIter = enemies.iterator();
while(eIter.hasNext()){
e = eIter.next();
if(ship.getBounds().overlaps(e.getBounds()))
Gdx.app.log(gameMain.LOG, "ColisioN!");
shipCount = shipCount +1;
}
bIter = bullets.iterator();
while(bIter.hasNext()){
b = bIter.next();
eIter = enemies.iterator();
while(eIter.hasNext()){
e = eIter.next();
if(e.getBounds().overlaps(b.getBounds())){
Gdx.app.log(gameMain.LOG, "!");
bIter.remove();
count = count +1;
if (count == 20) {
eIter.remove();
}
}
}
}
public void addBullet(Bullet b){
bullets.add(b);
}
public ArrayList<Bullet> getBullets(){
return bullets;
}
public void setRenderer(WorldRenderer wr){
this.wr = wr;
}
public WorldRenderer getRenderer(){
return wr;
}
public void dispose(){
}
}
Also, i tried to put a Thread.sleep(2000) after an enemy creation to the
next creation, but when i run the game the Screen frezzes, but the thread
is working because i used a System.out.println to print in console after
each creation. There is another option to delay the bucle without using
Thread.sleep?`

No comments:

Post a Comment