- Home /
Question by
Walter_Hulsebos · Jul 16, 2017 at 06:43 AM ·
mousepositionclampinverse
How should I Clamp a Mouseposition to a circle?
So basically I want to be able to move my mouse everywhere BUT the circle
I have tried this:
public Transform crosshair, ship;
public float rotationSpeed = 10f, radius = 5f;
void Start()
{
Cursor.visible = false;
}
void Update()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 cantTouchThis = ship.position;
Vector2 direction = mousePosition - cantTouchThis; //direction from Ship to Cursor
direction = Vector2.ClampMagnitude(direction, radius);
crosshair.position = cantTouchThis + direction;
}
Now how would I invert Vector2.ClampMagnitude(direction, radius) ?
cursorlock.png
(18.4 kB)
cursorlock.png
(18.4 kB)
Comment
Best Answer
Answer by Walter_Hulsebos · Jul 16, 2017 at 07:33 AM
I figured I didn't need to use Vector2.ClampMagnitude so I updated it to this:
public Transform crosshair, ship;
public float rotationSpeed = 10f, radius = 1f;
void Start()
{
Cursor.visible = false;
}
void Update()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 center = ship.position;
Vector2 direction = mousePosition - center; //direction from Center to Cursor
Vector2 normalizedDirection = direction.normalized;
crosshair.position = center + (normalizedDirection * radius);
}
I hope someone else can get something from it, if not. Sorry for the clutter.
Answer by Bunny83 · Jul 16, 2017 at 10:43 AM
ClampMagnitude ensures that the vector is not longer than the given length. The actual code behind ClampMagnitude is this:
public static Vector3 ClampMagnitude(Vector3 vector, float maxLength)
{
if (vector.sqrMagnitude > maxLength * maxLength)
return vector.normalized * maxLength;
return vector;
}
In order to invert the behaviour you just have to reverse the comparison from >
to <
public static Vector3 ClampMagnitudeMin(Vector3 vector, float minLength)
{
if (vector.sqrMagnitude < minLength * minLength)
return vector.normalized * minLength;
return vector;
}
I just realised you used Vector2, however the concept is still the same. You can replace Vector3 with Vector2