- Home /
Limit Lerp Distance From Target
I am currently creating an 2-d orb game, where the goal is to fire/"sling" the orb into the goal. This is the method that allows the user to pull back the orb (just before the player releases the mouse button, and the Fire() method is called):
void PullBackOrb(Vector2 mousePos)
{
if(Vector2.Distance(firePos, mousePos) < 3)
{
print("Orb exceeded max pullback distance");
//Limit Pullback distance (?)
}
Vector2 lerpPos = Vector2.Lerp(transform.position, mousePos, 10 * Time.deltaTime);
transform.position = lerpPos;
}
Is there a way to limit the distance the user can pull back the orb; if the user pulls the orb beyond a radius of 3 from the firePos; so even if the mouse is beyond the radius of 3, the orb will act like it must stay within the radius?
Answer by aldonaletto · Sep 30, 2012 at 09:11 PM
You could limit the distance mousePos-firePos like this:
void PullBackOrb(Vector2 mousePos){
if (Vector2.Distance(firePos, mousePos) > 3){
// find the mousePos offset from firePos:
Vector2 offset = mousePos - firePos;
// clamp the offset distance to 3:
offset = Vector2.ClampMagnitude(offset, 3);
// adjust mousePos to this distance:
mousePos = firePos + offset;
}
Vector2 lerpPos = Vector2.Lerp(transform.position, mousePos, 10 * Time.deltaTime);
transform.position = lerpPos;
}
This code follows the mouse pointer direction, but limits the orb position to a distance 3 from firePos.
Wow! I can't believe I didn't think to do it that way. I guess manually subtracting two vectors gives you a workable magnitude. I was trying to clamp the Vector2.Distance of those, and rework that in. It was a mess.
Thanks!
We're actually subtracting two points, which produces a vector. This vector's magnitude is the distance between the two points, and the very handy function Vector2.Clamp$$anonymous$$agnitude can clamp it to the desired value without affecting the vector direction.
Your answer
Follow this Question
Related Questions
[C#] can someone give me a detailed explanation of lerp 1 Answer
Vector3.Lerp result in "laggy" movement while running on iOS devices 2 Answers
Looking to see if the method I'm using for movement is correct or if I'm doing something wrong. 0 Answers
Difficulty with Vector2 Lerp, object jumping, not moving 2 Answers