1

My game is a simple 2D top down design style. I already have the enemies following the player but i don't know how to make the enemies face him. I don't even know where to begin.

Here's my code to make the enemies follow the player:

 if ( enemy.x > player.x ){
      enemy.x -= 7;
 }else {
      enemy.x += 7;
 {
 if ( enemy.y > player.y ){
      enemy.y -= 7;
 }else {
      enemy.y += 7;
 {
Aaron Beall
  • 49,769
  • 26
  • 85
  • 103
rtpenick
  • 125
  • 7

2 Answers2

2

I'm assuming you have a variable determining the enemy direction. Also, assuming you're just using the four cardinal directions.

You can just do a simple comparison of the enemies x,y coordinates compared to the player's.

sudo code:

if enemy x > player x // player is to the left of the enemy
    enemy face left
else if enemy x < player x // player is to the right of the enemy
    enemy face right
else if enemy y > player y // player is below the enemy
    enemy face down
else
    enemy face up

This will make your enemies almost always face left/right. You can get more involved once you get this working by comparing the deltas of the enemy x/y compared to the player x/y.

Something like:

delta x = abs(player x - enemy x)
delta y = abs(player y - enemy y)

if delta x > delta y // Enemy is further away on the x axis than the y axis
    make a choice of facing left/right
else
    make a choice of facing up/down

Hope this helps you get started.

Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
2

If you want the enemy to face exactly toward the player, in other words a full 360 degrees, you can calculate the angle between the enemy and the player and use the rotation property, like this:

var angle:Number = Math.atan2(player.y - enemy.y, player.x - enemy.x) * (180 / Math.PI);
enemy.rotation = angle;

For this to look right you should make your enemy's registration to be in its center so that it rotates around its center, and draw it facing rightward so that an angle of 0 is facing right.

Aaron Beall
  • 49,769
  • 26
  • 85
  • 103
  • I used this method. The enemy does face the player. But it's not clean and it doesn't always face the player directly var angle:Number = Math.atan2(myCar.y - mc_enemyCar02.y, myCar.x - mc_enemyCar02.x) * (180 / Math.PI); mc_enemyCar02.rotation = angle; – rtpenick Feb 12 '16 at 21:51
  • Not sure what you mean by "clean" and "direct", but it *will* always face the player precisely if your `myCar` and `mc_enemyCar` are in the same container. Otherwise you will have to convert your car coordinates to enemy car coordinate space: `var car:Point = enemyCarsContainer.globalToLocal(myCar.localToGlobal(new Point())`. Also make sure your enemy car is drawn *facing rightward exactly.* The math is correct, your graphics might be wrong. – Aaron Beall Feb 12 '16 at 22:50