I'm making an enemy follow the player based on his possition and attack if he is within a distance and his last movement (if the enemy last moved to the left, it will attack to the left, etc.). It attacks just fine left and right but not up or down. I tried watching frame by frame to see what happened and discovered that the enemy was twitching left and right to get to the player even if it was above or below him, which is the reason it is recording the last move to the left or right and not attacking top or bottom.
This is the code I use to update the position to where the enemy is going to move (pposX and Y is the player's current position and stillLock the last direction to where the enemy moved)
xMove = 0;
yMove = 0;
if(pposY < y){ //UP
yMove = -speed;
stillLock2 = 3;
}
if(pposY > y){ //DOWN
yMove = speed;
stillLock2 = 4;
}
if(pposX < x){ //LEFT
xMove = -speed;
stillLock2 = 1;
}
if(pposX > x){ //RIGHT
xMove = speed;
stillLock2 = 2;
And this is the method I call to create a rectangle with the range of the attack if the cooldown limit is met and hurt the player if it intersects it's collision bounds. (attack is a boolean var indicating enemy is ready to attack)
public void checkAttacks(){
attack2Timer += System.currentTimeMillis() - lastAttack2Timer;
lastAttack2Timer = System.currentTimeMillis();
if(attack2Timer < attack2Cooldown){
return;
}
Rectangle cb = getCollisionBounds(0, 0);
Rectangle ar2 = new Rectangle();
int arSize = 50;
ar2.width = arSize;
ar2.height = arSize;
/*
* Still lock diagram
* 1 = Left
* 2 = Right
* 3 = Up
* 4 = Down
*/
//creates collision rectangle
if(attack && stillLock2 == 3){ //UP
ar2.x = cb.x + cb.width / 2 - arSize / 2;
ar2.y = cb.y - arSize;
}else if(attack && stillLock2 == 4){ //DOWN
ar2.x = cb.x + cb.width / 2 - arSize / 2;
ar2.y = cb.y + cb.height;
}else if(attack && stillLock2 == 1){ //LEFT
ar2.x = cb.x - arSize;
ar2.y = cb.y + cb.height / 2 - arSize / 2;
}else if(attack && stillLock2 == 2){ //RIGHT
ar2.x = cb.x + cb.width;
ar2.y = cb.y + cb.height / 2 - arSize / 2;
}else
return;
attack2Timer = 0;
//if something above happened, check collisions
if(handler.getWorld().getEntityManager().getPlayer().getCollisionBounds(0, 0).intersects(ar2)){ //damages if player is there
handler.getWorld().getEntityManager().getPlayer().hurt(1);
return;
}
}
I would appreciate so much if anybody had an idea of how to fix this! (And I'm trully sorry about the code dump).