Search code examples
c++vector2dtrigonometryangle

C++ Move 2D Point Along Angle


So I am writing a game in C++, currently I am working on a 'Compass', but I am having some problems with the vector math..

Here is a little image I created to possibly help explain my question better enter image description here

Ok, so as you can see the 2D position of A begins at (4, 4), but then I want to move A along the 45 degree angle until the 2D position reaches (16, 16), so basically there is a 12 distance between where A starts and where it ends. And my qustion is how would I calculate this?


Solution

  • the simplest way in 2D is to take angle 'ang', and distance 'd', and your starting point 'x' and 'y':

    x1 = x + cos(ang) * distance;
    y1 = y + sin(ang) * distance;
    

    In 2D the rotation for any object can be just stored as a single value, ang.

    using cos for x and sin for y is the "standard" way that almost everyone does it. cos(ang) and sin(ang) trace a circle out as ang increases. ang = 0 points right along the x-axis here, and as angle increases it spins counter-clockwise (i.e at 90 degrees it's pointing straight up). If you swap the cos and sin terms for x and y, you get ang = 0 pointing up along the y axis and clockwise rotation with increasing ang (since it's a mirror image), which could in fact be more convenient for making game, since y-axis is often the "forward" direction and you might like that increasing ang spins to the right.

    x1 = x + sin(ang) * distance;
    y1 = y + cos(ang) * distance;
    

    Later you can get into vectors and matricies that do the same thing but in a more flexible manner, but cos/sin are fine to get started with in a 2D game. In a 3D game, using cos and sin for rotations starts to break down in certain circumstances, and you start really benefiting from learning the matrix-based approaches.