Calculate vector with given angle and length
Asked Answered
N

3

11

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.

Nosepiece answered 15/11, 2014 at 21:20 Comment(1)
When you say 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
D
13

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]
}
Divertimento answered 15/11, 2014 at 21:33 Comment(2)
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
1

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
Ibanez answered 31/1, 2021 at 15:59 Comment(0)
A
0

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.

Anatole answered 15/11, 2014 at 21:23 Comment(3)
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.