Clamping a vector to a minimum and maximum?

jmasterx picture jmasterx · Jun 9, 2010 · Viewed 12k times · Source

I came accross this: t = Clamp(t/d, 0, 1) but I'm not sure how to perform this operation on a vector. What are the steps to clamp a vector if one was writing their own vector implementation?

Thanks

clamp clamping a vector to a minimum and a maximum

ex:

pc = # the point you are coloring now
p0 = # start point
p1 = # end point
v = p1 - p0
d = Length(v)
v = Normalize(v) # or Scale(v, 1/d)

v0 = pc - p0

t = Dot(v0, v)
t = Clamp(t/d, 0, 1)

color = (start_color * t) + (end_color * (1 - t))

Answer

I think that once you state clearly what you mean you'll find that most of the work is done for you...

I'm guessing you want to limit the length of the vector quantity (rather than a vector data structure) to lie within a specified range without changing its direction, no?

So:

if (v.length > max)
   v.setlength(max)
else if (v.length < min)
   v. setlength(min)

where the implementation of length() and setlength() depend on how you have stored your vector.


If your vector is stored in (angle,magnitude) form this is nearly trivial. If stored in Cartesian form (ie. (x,y,z) ) you get length from the Pythagorian theorem and setlength should scale each commponent by a factor of desired_length/current_length.