# How can I move an enemy towards a player in AndEngine? [closed]

I want to move all enemy towards player but i can't do this.Is there any way by which i c an perform this task?

• What did you try? How do you move single units? – Marton Apr 3 '13 at 12:12
• i tried to move player but i want movement of player the enemy should follow the player and shoots the player. player is moving perfectly but enemy not? – Maan Apr 3 '13 at 12:15
• Search for Steering Behaviors, here a serie of articles about the topic: Understanding Steering Behaviors – JCM Apr 3 '13 at 14:05

I provide you information about how to code this thing. For example we have to create two classes player and enemy.

Player class contains code about player movement and firing of player towards enemy.

Enemy class contains code about enemy movement towards player and firing of enemy. For enemy movements towards player you have to use MoveModifier and provide data about player in this modifier.

This thing work perfect when player set at constant position but create problem when you move player object. To make this correct you have to unregister MoveModifier that was previously created and attach new MoveModifier with enemy.

Same thing goes repeated with all the enemies. Only once you have to prepare enemy class and your task is complete. I don't provide any code because of no need if you have further problem then add as comment.

Get the difference in positions on the x and y axis and use Pythagorean theorem to calculate the length

double dx = player.x - enemy.x;
double dy = player.y - enemy.y;
double length = Math.sqrt(dx * dx + dy * dy);


Normalize the differences in positions

double accelerationX = dx / length;
double accelerationY = dy / length;


Add the acceleration multiplied by a speed determined by you to move the enemy.

enemyPosition.x += (accelerationX * speed);
enemyPosition.y += (accelerationY * speed);


This is the linear algebra way. There is also a trigonometry way, however, this works fine.

Note: I am on my phone so this is all un tested and you will need to modify it to work with your code.

P.s - this code should be placed in an update method that gets called a certain amount of times per second

If you are using vectors:

Vector2 direction = player.position - enemy.position;
direction.normalize();
enemy.position += direction * enemy.speed;