i have a texture attached to the Input.mousePosition. so when i move mouse around
texture follows the mouse. i want to limit the area of movement to the circle. so mouse
can go outside the circle but the texture should stick to the border of the circle. here is
a image that could help. i guess it is a simple math, but i just cant figure out how to control what is used and what not
Well, you can determine if it’s contained within the circle by seeing of the distance between the mouse point and the center of the circle is less than the radius.
if(distanceSqr < radiusSqr)
{
newPosition = mousePosition;
}
else
{
//This is where it needs to be clamped to the edge of the circle. The best method of doing this is to take the normalized direction from the center to the mouse position, and then multiply it by the radius so that it is at a point on the edge. Add that to the center of the circle and you get the position at the edge of the circle that is nearest to the mouse position.
newPosition = center + ((mousePosition - center).normalized * radius);
}
Since you said circle I assume you want to do this in 2D using a GUITexture, not in 3D space using a textured plane. Below is a function to limit the position of the texture inside a 2D circle, please keep in mind I just now wrote it and have not tested it.
public void ClampPositionToCircle(Vector2 center, float radius, ref Vector2 position)
{
// Calculate the offset vector from the center of the circle to our position
Vector2 offset = position - offset;
// Calculate the linear distance of this offset vector
float distance = offset.magnitude;
if (radius < distance)
{
// If the distance is more than our radius we need to clamp
// Calculate the direction to our position
Vector2 direction = offset / distance;
// Calculate our new position using the direction to our old position and our radius
position = center + direction * radius;
}
}
thanks everybody, i used Shawn[QS]'s example and it works good
you made a mistake at the line where you calculated Vector2 offset = position - offset;
should be var offset : Vector2=position-center;
That’s exactly the same method that I posted to your Unity Answers thread.
It’s not that big of a deal, but if you’re going to cross-post to the forums and UA, it’s helpful if you include a cross-link in each thread to the other thread. Since a lot of people participate both here and on UA, cross-posting to both forums tends to result in duplicated effort (just like in this case). If you cross-link, then at least people can check the other thread and see if the question’s already been answered.