Nichos
Nichos

Reputation: 33

Java: Enemy follow Player

I have an enemy and a player. What I am trying to do is have my enemy continuously follow my player while he moves. I have code that does that, but the speed of the goblin is different depending on where my character is relative to the enemy: such as when I'm up and to the left of the enemy (negative of the enemy), it moves super fast and is in my player. However, when I'm down and to the right (positive of the enemy) every thing is fine. Any ideas?

Here is what I have in my enemy update function:

        MoveToX = Board.playerOne.getX();
        MoveToY = Board.playerOne.getY();

        float distance = (float) Math.sqrt(Math.pow(MoveToX - x, 2) + Math.pow(MoveToY - y, 2));

        amountToMoveX = (((MoveToX - x) / distance) * speed);
        amountToMoveY = (((MoveToY - y) / distance) * speed);

        x+= amountToMoveX;
        y += amountToMoveY;

EDIT:

        //x is the enemies (this x) and the same for y


        int MoveToX = Board.playerOne.getX();
        int MoveToY = Board.playerOne.getY();

        int diffX = MoveToX - x;
        int diffY = MoveToY - y;

        float angle = (float)Math.atan2(diffY, diffX);

        x += speed * Math.cos(angle);
        y += speed * Math.sin(angle);

My new algorithm is this. However I am getting the same issue which is that my enemy moves as fast as me while its negative to the player.

Upvotes: 0

Views: 6674

Answers (1)

user3490218
user3490218

Reputation:

int diffX = moveToX - x;
int diffY = moveToY - y;

float angle = (float)Math.atan2(diffY, diffX);

x += speed * Math.cos(angle);
y += speed * Math.sin(angle);

diffX and diffY are the components of the vector from the enemy to the player. With that, you can calculate the angle by taking the arctangent of the components of the vector. Math.cos(angle) is the normalized x component of the distance vector <diffX, diffY>-> (cos^2(x) + sin^2(x) = 1), and multiplying that by speed gives you the velocity at which the enemy moves in the x direction. The same rules apply for y and Math.sin(angle).

Upvotes: 1

Related Questions