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.
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∘)).
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]
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With