2
$\begingroup$

I was wondering if there is a formula to clamp distance between two Vectors. Let me elaborate.

I have two Vectors, say, $V_1(x_1,y_1)$ and $V_2(x_2,y_2)$. I can find the distance '$d$' between them using $\sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}$.

Now, I want to clamp $d$ to, say $5$, if $d>5$, and I know $v_1$, which is the initial position. I also know the current value of $v_2$. However, I want to calculate $v_3$, which lies in between the two points which form a straight line, for which $d=5$ from $v_1$. And is collinear to the line formed from $v_1$ and $v_2$.

Any help is appreciated.

$\endgroup$
1
  • $\begingroup$ Formatting would be appreciated :) $\endgroup$
    – Zach466920
    Commented Apr 30, 2015 at 21:03

1 Answer 1

2
$\begingroup$

If all you care about is clamping, then you could just use the max function: $$ d = \max\left\{5, \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}\right\} $$ Otherwise, if you also want to compute $(x_3, y_3)$, then you can take advantage of similar triangles and use the following pseudocode:

dx = x2 - x1
dy = y2 - y1
d = sqrt(dx^2 + dy^2)
if d > 5
    x3 = x1 + 5*dx/d
    y3 = y1 + 5*dy/d
    d = 5
$\endgroup$
2
  • 1
    $\begingroup$ Thanks. Just a slight typo though, d assignment should be after the calculation of x3, y3.. $\endgroup$
    – gameOne
    Commented Apr 30, 2015 at 22:02
  • $\begingroup$ @gameOne Thanks, fixed it. $\endgroup$
    – Adriano
    Commented Apr 30, 2015 at 22:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .