Bobdinator
Bobdinator

Reputation: 137

Calculate vector with given angle and length

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.

Upvotes: 11

Views: 11650

Answers (3)

Alexander Schmidt
Alexander Schmidt

Reputation: 5723

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

Upvotes: 1

Marcus McLean
Marcus McLean

Reputation: 1326

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]
}

Upvotes: 13

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21748

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.

Upvotes: 0

Related Questions