Angle between points
geometryfunctionjavascriptarchivedAngle from Coordinates
Finding angles between two points is a common requirement. For example, you want your character to move or fire in the direction of the mouse cursor, or you want a character to turn to face something on the map.
The method for finding the angle between 2 coordinates is as follows:
function getAngle(x, y, x2, y2)
{
var a = Math.atan2(y2 - y, x2 - x);
return a < 0 ? a + (Math.PI * 2) : a;
}
Example source code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ctx = null, game = null;
var mouseX = -1, mouseY = -1;
var circleX = 300, circleY = 200, circleR = 75;
var degrees = 2*Math.PI;
var degrees360 = 360;
window.onload = function() {
game = document.getElementById('game');
ctx = game.getContext('2d');
ctx.font = "bold 10pt sans-serif";
game.addEventListener('mousemove', function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
var p = game;
do
{
mouseX-= p.offsetLeft;
mouseY-= p.offsetTop;
p = p.offsetParent;
} while(p!=null);
degrees = getAngle(circleX, circleY, mouseX, mouseY);
degrees360 = ((degrees/Math.PI * 180) + 450) % 360;
});
requestAnimationFrame(drawGame);
};
function getAngle(x, y, x2, y2)
{
var a = Math.atan2(y2 - y, x2 - x);
return a < 0 ? a + (Math.PI * 2) : a;
}
function drawGame()
{
if(ctx==null) { return; }
ctx.fillStyle = "#ffffff";
ctx.fillRect(0,0,600,400);
ctx.fillStyle = "#ccccff";
ctx.strokeStyle = "#990000";
ctx.beginPath();
ctx.arc(circleX, circleY, circleR, 0, degrees);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.arc(circleX, circleY, circleR, (Math.PI*1.5), degrees);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "#ff0000";
ctx.fillText("Angle (radians): " + degrees.toFixed(3), 10, 20);
ctx.fillStyle = "#0000cc";
ctx.fillText("Angle (degrees): " + degrees360.toFixed(3), 10, 40);
requestAnimationFrame(drawGame);
}
</script>
</head>
<body>
<p>Move your mouse around the circle below.</p>
<p>If you do not see a circle, check your browser supports Canvas elements, and has Javascript enabled.</p>
<canvas id="game" width="600" height="400"></canvas>
</body>
</html>