Skip to content Skip to sidebar Skip to footer

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 'move

Solution 1:

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

functionmyFunction(xCoord, yCoord, angle, length) {
    length = typeof length !== 'undefined' ? length : 10;
    angle = angle * Math.PI / 180; // if you're using degrees instead of radiansreturn [length * Math.cos(angle) + xCoord, length * Math.sin(angle) + yCoord]
}

Solution 2:

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:

functiongetRelativeVector(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

Solution 3:

The shift in x coordinate is L*cos(a) and shift in y coordinate is L*sin(a), where a is the angle ("direction given") and L is 10 px in your case.

Post a Comment for "Calculate Vector With Given Angle And Length"