• Question
  • i need help with tracking the closest enemy in my game

ok so @Letti42 told me how already but im kinda dumb of how it works, please someone tell me how to implement it so the sprite can move to that said enemy.

(never thought the pythagorean therom was useful)

 hypoDefender=Math.sqrt(Math.pow((defenders[e].x - enemies[i].x),2) +  Math.pow((defenders[e].y - enemies[i].y),2));
      if(hypoDefender < leastDist)leastDist = hypoDefender, closestEnemy = enemies[i];

    why do you need the Pythagorean theorem? the pythagorean theorem is for finding the distance of a hypotenuse, not for moving a sprite...

      person that's exactly the point, the pythagorean theorem was used to get the closest enemy... the two points create a right triangle, and measuring the hypotenuse will get you the distance between them. You sort through those distances and find the shortest length, getting you the closest enemy

        Letti42 i guess so, but dont you just need to find the angle to the enemie and use that?

          person
          no you're just finding the distance to determine the closest enemy

          pluto
          i've given several similar answers before, anyways what you wanna do is find the angle from the enemy to the player and have the enemy move in accordinance with some trig wave crap
          var angleFromEnemyToPlayer = atan2(defenders[e].y - enemies[i].y, defenders[e].x - enemies[i].x);
          // ^ trig crap function ^
          enemies[i].x += cos(angleFromEnemyToPlayer)*enemies[i].movementSpeed;
          enemies[i].y += sin(angleFromEnemyToPlayer)*enemies[i].movementSpeed;
          // ^ mor trig crap function ^

          don't worry if you didn't or still don't understand all the trig stuff, I'm in algebra 2 and i still don't know why I have to use atan2 for this.
          just understand that atan2 somehow gets the angle from one point to another, and that cos and sin make little waves offset by pi or something(good for animations btw)

          im in math 1 (i have no clue wtf math 1 is it's just what they call it) and i still dont understand why we need the distance for any of this

          Chat