Point given Angle and Distance

Fri May 02 2025 15:06:07 GMT+0100 (British Summer Time) geometryfunctionjavascriptarchived

Plotting relative point at Angle and Distance

This method is useful for plotting a relative point in 2D space, given a start point, an angle and the desired distance.

View example

You might use this method for having a character fire along a specific path, or plot a relative movement.

The method is as follows:


function pointAtAngleDistance(x, y, deg, dist)
{
    return [(dist * Math.cos(deg)) + x,
        (dist * Math.sin(deg)) + y];
}

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;
var targetPoint = [300, circleY-circleR];

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);
        targetPoint = pointAtAngleDistance(circleX, circleY, degrees, circleR);
        degrees360 = ((degrees/Math.PI * 180) + 450) % 360;
    });
function getAngle(x, y, x2, y2)
{
    var a = Math.atan2(y2 - y, x2 - x);
    return a < 0 ? a + (Math.PI * 2) : a;
}
    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 pointAtAngleDistance(x, y, deg, dist)
{
    return [(dist * Math.cos(deg)) + x,
        (dist * Math.sin(deg)) + y];
}

function drawGame()
{
    if(ctx==null) { return; }

    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0,0,600,400);


    ctx.fillStyle = "#aaaacc";
    ctx.strokeStyle = "#7777aa";

    ctx.beginPath();
    ctx.arc(circleX, circleY, circleR, 0, (Math.PI*2));
    ctx.stroke();

    ctx.fillStyle = "#ffffaa";
    ctx.strokeStyle = "#aa0000";

    ctx.beginPath();
    ctx.arc(targetPoint[0], targetPoint[1], 5, 0, (Math.PI*2));
    ctx.fill();
    ctx.stroke();

    ctx.fillStyle = "#ff0000";
    ctx.fillText("Angle (radians): " + degrees.toFixed(3), 10, 20);
    ctx.fillText("Angle (degrees): " + degrees360.toFixed(3), 10, 40);
    ctx.fillText("Target: " + targetPoint[0].toFixed(2) + ', ' + targetPoint[1].toFixed(2), 10, 60);

    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>