Hello everyone.
I want to constrain a circle I created in my project using a rectangle. I watched a few videos and they generally use the same method, but this method does not give the result I want.
I have prepared a visual demo for you below.
I want to constrain the angle I give using the blue circle with the red rectangle. You can see the angle as the green line. The little white circle is the value I got.
This method works correctly when the angle is 0,90,180,270 etc. However, as you can see below, it does not give the desired result for other values.
The value I want should be exactly on the green line.
Here’s my code for this demo:
using UnityEngine;
public class CircleLimiter : MonoBehaviour
{
public Vector2 rectangleSize;
public float circleRadius;
public float angle;
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(Vector3.zero, rectangleSize);
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(Vector3.zero, circleRadius);
Gizmos.color = Color.green;
Vector3 positionByAngle = new Vector3(Mathf.Cos(angle * Mathf.Deg2Rad) * circleRadius, Mathf.Sin(angle * Mathf.Deg2Rad) * circleRadius);
Gizmos.DrawLine(Vector3.zero, positionByAngle);
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(Limit(positionByAngle, rectangleSize), 0.2f);
}
Vector2 Limit(Vector2 position, Vector2 limit)
{
limit /= limit;
return new Vector2(
Mathf.Clamp(position.x, -limit.x, limit.x),
Mathf.Clamp(position.y, -limit.y, limit.y)
);
}
}
I would be very grateful if you could answer my question or direct me to related topics. Thanks in advance.