Unity - Check if point is inside the camera view.
First we will get the x, y coordinates of the camera relative to the Viewport this will ensure that we'll have the edges of the camera view no matter the aspect ratio of it.
Ps. I use this Range struct just because i prefer to read min, max instead of x, y in this situations where i have a min, max value.
[System.Serializable]
public struct Range
{
/// <summary>
/// Returns a random value between min and max.
/// </summary>
public float Value { get { return Random.Range(min, max); } }
public float min;
public float max;
public Range(float min, float max)
{
this.min = min;
this.max = max;
}
}
public static Range VerticalLimit;
public static Range HorizontalLimit;
public static Camera MainCamera;
private void Awake()
{
MainCamera = Camera.main;
Vector2 __minLimits = MainCamera.ViewportToWorldPoint(new Vector2(0.0f, 0.0f));
Vector2 __maxLimits = MainCamera.ViewportToWorldPoint(new Vector2(1.0f, 1.0f));
VerticalLimit = new Range(__minLimits.y, __maxLimits.y);
HorizontalLimit = new Range(__minLimits.x, __maxLimits.x);
}
Then we can simply check if a passed point is inside within the min and max Range of the camera view world boundaries.
public static bool InsideCamera(Vector2 p_position)
{
if (p_position.x < HorizontalLimit.min || p_position.x > HorizontalLimit.max)
return false;
if (p_position.y < VerticalLimit.min || p_position.y > VerticalLimit.max)
return false;
return true;
}