Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate vector with given angle and length

Is there any way in which, in javascript, I can call a function with an x and y co-ord and a direction (angle in degrees) and it will return a set of new co-ords that has been 'moved' by 10px in the direction given from the original co-ords? I looked around but all I can find is ways to get the angle of two given co-ords.

like image 555
Bobdinator Avatar asked Nov 15 '14 21:11

Bobdinator


People also ask

How do you find a vector given an angle?

Similarly, the angle the vector →u makes with the Y-axis is 10∘. Hence, the y component of the vector is |→u|cos(10∘). Hence, if you want write the vector as (x,y), then it should be (3cos(80∘),3cos(10∘)).


2 Answers

This function returns an array [xCoord, yCoord] of the new coordinates:

function myFunction(xCoord, yCoord, angle, length) {
    length = typeof length !== 'undefined' ? length : 10;
    angle = angle * Math.PI / 180; // if you're using degrees instead of radians
    return [length * Math.cos(angle) + xCoord, length * Math.sin(angle) + yCoord]
}
like image 154
Marcus McLean Avatar answered Oct 24 '22 05:10

Marcus McLean


I just wanted to point out, that the answers of are not correct IMHO. I've created a JSFiddle showing that the correct implementation must be something like this:

function getRelativeVector(angle, length, xOffset, yOffset) {
    angle = angle * Math.PI / 180; 
    return { 
        X:length * Math.sin(angle) + xOffset, 
        Y:length * Math.cos(angle) + yOffset 
    };
}

The other solutions shown here from @Audrius and @Markus are simply twisted in cos and sin. They are working for angles between 0 and 45 degrees only.

The formula would be:

  • X = length * sin(angle) + xLocation
  • Y = length * cos(angle) + yLocation
like image 25
Alexander Schmidt Avatar answered Oct 24 '22 06:10

Alexander Schmidt