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?
closed as too broad by bummzack, Sean Middleditch, Anko, Seth Battin, MichaelHouse♦ Jul 25 '13 at 13:11
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
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;