Calculate vector with given angle and length
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
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]
}