矩形の外周を回るオブジェクトを表現したいときに使います。
ベクトルは中心からです。四角い時計を想像してもらえればわかりやすいと思います。
public static Vector2 GetRectEdgeCrossPointFromCenter(Vector2 direction, Rect rect)
{
float dot_vertical = Vector2.Dot(Vector2.up, direction);
float dot_horizon = Vector3.Dot(Vector2.right, direction);
Vector2 v_vertical = Mathf.Sign(dot_vertical) * Vector2.up;
Vector2 v_horizon = Mathf.Sign(dot_horizon) * Vector2.right;
float rad_vertical = Vector2.Angle(direction, v_vertical) / 180 * Mathf.PI;
float rad_horizon = Vector2.Angle(direction, v_horizon) / 180 * Mathf.PI;
float tan_horizon = float.NaN;
float tan_vertical = float.NaN;
if (dot_vertical != 0)
{
tan_horizon = Mathf.Tan(rad_vertical);
if (Mathf.Abs(tan_horizon) > 1.0f) { tan_horizon = float.NaN; }
}
if (dot_horizon != 0)
{
tan_vertical = Mathf.Tan(rad_horizon);
if (Mathf.Abs(tan_vertical) > 1.0f) { tan_vertical = float.NaN; }
}
Vector2 edge_cross_point = rect.center;
if (!float.IsNaN(tan_horizon))
{
edge_cross_point += v_vertical * rect.height * 0.5f;
edge_cross_point += v_horizon * rect.height * 0.5f * tan_horizon;
}
else if (!float.IsNaN(tan_vertical))
{
edge_cross_point += v_horizon * rect.width * 0.5f;
edge_cross_point += v_vertical * rect.height * 0.5f * tan_vertical;
}
return edge_cross_point;
}