Search code examples
javascriptangle

Does anyone know what angle it should be?


I've got myself a game, the shooting of the player is working fine but that's because I'm using an on.click event and some maths but now I'm trying to get the enemy to shoot back to my player.

me is just the enemy, so me.x and me.y is the x and the y of the enemy.

p is the player so p.x and p.yis the x and the y of the player.

We are trying to shoot from the me.x and m.y to the p.x and p.y.

As the code stands now it justs shoots randomly every second to the right.

The canvas is 500x500.

me.angle = Math.atan2(p.x, p.y) / Math.PI * 180;

 me.fireBullet = function (angle) {
  var b = Bullet(me.id, angle); //bullet id, with angle pack
   b.x = me.x;
   b.y = me.y;
  }

   setInterval(function () {
     me.fireBullet(me.angle); //target angle attack
     }
       , 1000);
    }

Solution

  • The fix was to find the difference between x and y took me a couple of tries but its working now.

    var differenceX = p.x - me.x; //players x - targets x
    var differenceY = p.y - me.y; //players y - targets y
    
    me.angle = Math.atan2(differenceY, differenceX) / Math.PI * 180