8-direction consistent movement speed in all directions, how to get angle of movement from direction keys?
<p>Top of the morning to ye people on various surfaces of earth.</p>

<p>The problem: How to get the angle of direction from the arrow keys.</p>

<p>Preamble: The standard way to move in a basic top-down game is to add to x and/or y from within an update method, depending on the direction.</p>

<pre><code>if (moveUp)     playerY -= delta * speed;
if (moveDown)   playerY += delta * speed;
if (moveLeft)   playerX -= delta * speed;
if (moveRight)  playerX += delta * speed;
</code></pre>

<p>This is elegant for 4-direction movement (I believe) because no matter what key combinations are pressed, the direction of movement will be consistent.  Eg pressing up-down-left will move left, as up and down cancel out.  But when moving diagonally, the steps will be too large.  If speed is 20, moving left will move left by 20 per second, up will move up by 20 per second.  But moving up-left will move by a little over 28.24 per second.</p>

<p>The solution here is to use cos and sin to get the new x and y, which is easy once you know the angle:</p>

<pre><code>playerX += Math.cos(Math.toRadians(angle)) * delta * speed;
playerY -= Math.sin(Math.toRadians(angle)) * delta * speed; //y is inverted
</code></pre>

<p>But, for me at least, this raises a new problem: what's the angle?  In my KeyListener I'm currently setting/clearing booleans for each arrow key.  I can use a bulky set of if statements:</p>

<pre><code>if (moveUp)     angle = 90;
if (moveDown)   angle = 270;
if (moveRight)  angle = 0;
if (moveLeft)   angle = 180;
if (moveUp &amp;&amp; moveLeft)     angle = 135;
if (moveUp &amp;&amp; moveRight)    angle = 45;
if (moveDown &amp;&amp; moveLeft)   angle = 225;
if (moveDown &amp;&amp; moveRight)  angle = 315;
//...etc... for all combinations
</code></pre>

<p>For the life of me, I cannot find a sexy way to get the movement angle from what direction keys are pressed down.  It strikes me like this should be a common problem, game design 101, but intense googling hasn't led me to anything (made harder by the fact that it's difficult to put the problem into words).  In all instances of examples, either they just retained the diagonal-is-faster functionality (as with my first snippet), or know the angle ahead of time (ie. move towards the mouse), or are 2D side scrollers.  </p>

<p>Surely there's a sexy mathy way (or something) to work it out in a few lines?  Or am I approaching this completely wrong?</p>

<p>Edit: Post-answer code (as posted by korona below):</p>

<pre><code>double x=0, y=0;
if (moveLeft) x -= 1;
if (moveRight) x += 1;
if (moveUp) y -= 1;
if (moveDown) y += 1;

double length = Math.sqrt(x * x + y * y);
if (length != 0) {
    x /= length;
    y /= length;

    x *= delta*speed;
    y *= delta*speed;

    playerX += x;
    playerY += y;
}
</code></pre>
