Search code examples
iosmacosvectorcore-graphics

Limit CGVector's length while keeping its direction


I need to move between two SpriteKit nodes with a CGVector, whose length is, for example, 100 (red arrow).

But I want to limit the vector's length to 70, if it's more than 70 (green arrow). So, I need to "cut" the red vector's length, but keep its direction.

Drawing of a vector showing actual length and limited length

How can I do that?


Solution

  • Say you have a variable v of type CGVector. First, you compute its length:

    double len = hypot(v.dx, v.dy);
    

    Then, if it's greater than 70, you divide both components by len and multiply by 70 to make the vector's length equal to 70:

    if (len > 70.0)
    {
        v.dx *= 70.0 / len;
        v.dy *= 70.0 / len;
    }