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.
Calculate vector with given angle and length
11k Views Asked by Bobdinator At
3
There are 3 best solutions below
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.
0

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: