Diagonal hero movement - harder than it seems!

hero walking at a 45 degree angle

hero walking at a 45 degree angle

The hero now moves diagonally, and faces in the appropriate direction. This took some actual trigonometry to figure out the angle based on the vertical and horizontal displacement. To be honest, it’s overkill right now, as we’re only using keyboard arrows, so there are only 8 possible rotations, all divisible by 45 degrees. However, we may eventually add mouse pointer-based movement to an arbitrary rotation, so our work today should hopefully make that a bit easier. If any of you code geeks out there are interested, here’s the relevant source section, taken from the hero’s frame event handler:

  1. // we derive the rotation and speed based on the angle and length of
  2. //   the hypotenuse given by netX & netY
  3. // handle special cases on the axes first:
  4. if (netY == 0)
  5. {
  6.         if (netX == 1)
  7.                 rotation = 90;
  8.         else if (netX == -1)
  9.                 rotation = 270;
  10. }
  11. else if (netX == 0)
  12. {
  13.         if (netY == 1)
  14.                 rotation = 180;
  15.         else if (netY == -1)
  16.                 rotation = 0;
  17. }
  18. // now handle arbitrary angles:
  19. else
  20. {
  21.         rotation = 90 + Math.atan(netY / netX) * 180 / Math.PI;
  22.         if (netX < 0)
  23.         {
  24.                 rotation += 180;
  25.         }
  26. }
  27.  
  28. // normalize speed by dividing by the length of hypotenuse:
  29. var hypLength:Number = Math.sqrt(netX * netX + netY * netY) || 1;
  30. var speedAdjust:Number = 1 / hypLength;
  31. position.x += runSpeed * netX * speedAdjust;
  32. position.y += runSpeed * netY * speedAdjust;

In addition, I’ve always thought it important to not give a bonus to movement just because you’re moving both horizontally and vertically at the same time. So I used the old standard geometry formula for determining the lengths of each side of a right triangle (a2 + b2 = c2) and the movement displacement is now divided by the correct ratio to make effective speed the same no matter which direction the hero moves. Again, probably not vital at this point, but hey, it’s the little things that make it special. :)

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>