I have an List that contains type Enemy, I populate this list using the below loop:
for(....) {
arrayEnemy.add(new Enemy(new Rectangle(50.50f, 50.50f,
Enemy.WIDTH, Enemy.HEIGHT),
facesRight? 0.10f : -0.10f, 0.7f));
}
and cheking objects Enemy:
if(arrayEnemy.get(num).isDie){
arrayEnemy.get(num).rendCountAnim++;
arrayEnemy.get(num).setStateEnemy(Enemy.StateEnemy.Deadening);
arrayEnemy.get(num).getStateEnemy();
if (TimeUtils.millis()>(arrayEnemy.get(num).startTimeAnim+35100)) {
arrayEnemy.removeIndex(num);
break;
}
}
The Enemy class:
public class Enemy {
enum StateEnemy {
Walking, Deadening
}
public StateEnemy stateEnemy = StateEnemy.Walking;
static float WIDTH;
static float HEIGHT;
public boolean isDie = false;
private Rectangle rect;
private float velocityX;
private float velocityY;
public long startTimeAnim = TimeUtils.millis();
public int rendCountAnim = 0;
public Enemy(Rectangle rect, float velocityX, float velocityY) {
this.rect = rect;
this.WIDTH=rect.width;
this.HEIGHT=rect.height;
this.velocityX = velocityX;
this.velocityY = velocityY;
}
public StateEnemy getStateEnemy() {
return stateEnemy;
}
public void setStateEnemy(StateEnemy stateEnemy) {
this.stateEnemy = stateEnemy;
}
public void moveX() {
rect.x += velocityX;
}
public void moveY() {
rect.y += velocityY;
}
public float getOldPointCellX(){
return oldPointCellX;
}
public float getOldPointCellY(){
return oldPointCellY;
}
public Rectangle getRect() {
return rect;
}
public float getVelocityX() {
return velocityX;
}
public void setVelocityX(float velocity) {
this.velocityX = velocity;
}
public float getVelocityY() {
return velocityY;
}
public void setVelocityY(float velocity) {
this.velocityY = velocity;
}
}
They are all walking on the ground, as expected. BUT!!! I kill one of the enemies, but ALL of the enemies animations change! This is the render method code:
TextureRegion frameEnemy = null;
if(arrayEnemy.size != 0){
switch (arrayEnemy.get(num).getStateEnemy()) {
case Walking:
frameEnemy = animWalkEnemy.getKeyFrame(stateTime);
break;
case Deadening:
frameEnemy = animDeadEnemy.getKeyFrame(stateTime);
break;
}
}
for(num=0; num < arrayEnemy.size; num++){
batch.draw(frameEnemy, arrayEnemy.get(num).getRect().x,
arrayEnemy.get(num).getRect().y,
Enemy.WIDTH, Enemy.HEIGHT);
}
How can I make the animation occur on a single instance of the Enemy instead of all of them?
Like DavidS pointed out in the comments, you should set the frameEnemy
for each Enemy
object separately. You can do this as follows
for(Enemy enemy : arrayEnemy) {
//Set the animation texture for the enemy object
switch (enemy.getStateEnemy()) {
case Walking:
frameEnemy = animWalkEnemy.getKeyFrame(stateTime);
break;
case Deadening:
frameEnemy = animDeadEnemy.getKeyFrame(stateTime);
break;
}
//Render the enemy object
batch.draw(frameEnemy, enemy.getRect().x, enemy.getRect().y, Enemy.WIDTH, Enemy.HEIGHT);
}