1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rectの中心からのベクトルと辺の交差点を求める

Posted at

矩形の外周を回るオブジェクトを表現したいときに使います。
ベクトルは中心からです。四角い時計を想像してもらえればわかりやすいと思います。

    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;
    }



1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?