Search code examples
javascriptmathangle

Calculating cordanates with angles


So basically I have the starting vectors and the angels but the code I'm working with only updates my angle and I'm trying to get to another vector.

var start_x = 0;
var start_y = 0;
var speed = 200;
var current_x; //This needs to be calculated 
var current_y; //This needs to be calculated 
var current_angle = 53;

How could I calculate the current X vector and Y vector using the speed and the starting positions? I've browsed around this site and others but I cant seem to find an answer.


Solution

  • Okay there you your question in graph representation

    Firstly you have speed, so you need to take a time frame too so let us assume we need the co-ordinates after 1s. The formula to measure Speed is V = S/T where V is velocity(speed in a direction) S is distance and T is time. Therefore S = VxT According to your speed 200, Distance travelled in 1 second is 200M now we have the angle too which you gave it as 53deg. Hence we can draw an imaginary triangle to find (x,y) the new co-ordinates which are unknown. To know x,y the formula is

    y= sin(theta) x Distance
    x = cos(theta) x Distance
    

    where theta is equal to 53deg and distance is 200 hence (x,y) = ()

    To be a bit more descriptive, in our imaginary triangle y is opposite and x is adjacent, and x,y are nothing but distances from 0,0 . There is a formula in trigonometry, which states that

    Sin(theta) = opposite/Hypotenuse
     hence 53 = unknown/200
    similarly
    Cos(theta) = Adjacent/Hypotenuse
     hence 53 = unknown/200
     So after calculating we get the result (120.36,159.72)
    

    So in java script you can use

    // since Math.cos takes input in radians you  have to convert it into degrees.
    
        var speed = 200;
        var time = 1;
        var angle = 53;
        x = (Math.cos(angle*(Math.PI/100))* (speed*time);
        y = (Math.sin(angle*(Math.PI/100))* (speed*time);
    

    We have calculated using radians not degrees, so you might need necessary conversion into degrees but thats not difficult just interchange (x,y) to (y,x) which would be the result with degrees.