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
Asked Answered
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]
}
no point in using
!==
operator, !=
will do just fine since you know you are comparing it to a string and you know typeof
returns a string. –
Babel You're right,
!=
will be sufficient, but using the strict equality operators !==
and ===
is a recommended best practice as it doesn't encourage type coercion, which is carried out by unmemorable rules. –
Divertimento 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
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.
When I do
10*Math.cos(90)
it returns -4.480736161291702, if 90 degrees is right, shouldn't that just be 10? –
Nosepiece See my response.
Math.cos()
and Math.sin()
take angles measured in radians as their arguments, so you'll need to convert degrees into radians (see the comment in my code). –
Divertimento oh I see, this uses radians instead of degrees, probably should have specified that. –
Nosepiece
© 2022 - 2024 — McMap. All rights reserved.
Direction
, how do you plan on describing this? For example - you could you an angle (θ) relative to the x axis. The method of describing this is important to your answer. javascript is really irrelevant as the implementation would be the same regardless of the language. – Coreligionist