Search code examples
mathvector-graphicspi

Set vector2 coordinates by move distance and degree


I have a Vector2 in my 2D Game and what I would like to do now is set my vector2 x and y by calculating them using rotation in degrees

Do I need to use PI to calculate new X and Y coordinates then add move distance per second in order to get the correct coordinates?

Example : Lets say degree is 90, which means my gameobject would move forward,at 5 floating units per second, then Y would be 5,10,15 and if degree would be 180 then X would increase by 5 every second, this is simple, but how to do it for other degrees such as 38,268 etc?


Solution

  • The usual convention is that 0 degrees points in the positive X direction and as the angle increases you rotate the direction anti-clockwise. Your convention seems to be that 0 degrees points in the negative X direction and the angle increases clockwise, so first of all you must translate your angle, say alpha, into one with the usual convention, say beta

    beta = 180.0 - alpha
    

    Next, trigonometric functions assume radians which run from 0 to 2π rather than from 0 to 360, so you must translate beta into an angle in radians, say theta

    theta = 2.0*PI*beta/360.0
    

    Finally, cos(theta) gives the change in X for a move of 1 unit in the direction given by theta and sin(theta) gives the change in Y. So you need

    X = X + D * cos(theta)
    Y = Y + D * sintheta)
    

    for a distance D. Using your convention this translates to

    X = X + D * cos(2.0*PI*(180.0-alpha)/360.0)
    Y = Y + D * sin(2.0*PI*(180.0-alpha)/360.0)