1
0

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 1 year has passed since last update.

【Unity】円内の格子点を返す関数

Posted at

概要

gif.gif
円内の格子点をVector2[]で返す関数を作りました。左下を0にする引数もあります。
円内の判定に自信が無いのでコメントを頂けると助かります(if (x * x + sqrY - sqrRadius <= -0.5f))。

コード

お手持ちの MathUtil クラスに追加してご利用ください。

円内の格子点を返す関数.cs
public static List<Vector2> GridPointsInCircle(int diameter, bool bottomLeftCenter)
{
    if (!bottomLeftCenter) return GridPointsInCircle(diameter);
    var list = GridPointsInCircle(diameter);
    var offset = Vector2.one * (diameter * 0.5f - 0.5f);
    for (int i = list.Count - 1; i >= 0; i--) list[i] += offset;
    return list;
}
public static List<Vector2> GridPointsInCircle(int diameter)
{
    if (diameter <= 1)
    {
        if (diameter == 0) return new List<Vector2>();
        return new List<Vector2>() { Vector2.zero };
    }

    var odd = diameter % 2 == 1 ? 0.5f : 0f;
    var radius = diameter * 0.5f;
    var sqrRadius = radius * radius;
    var list = new List<Vector2>();
    var prevX = radius + 0.5f;

    for (var y = 0.5f + odd; y <= radius; y += 1f)
    {
        var sqrY = y * y;
        for (var x = prevX; x >= 0; x -= 1f)
        {
            if (x * x + sqrY - sqrRadius <= -0.5f)
            {
                for (float i = x; i >= -x; i -= 1f)
                {
                    list.Add(new Vector2(i, y));
                    list.Add(new Vector2(i, -y));
                }
                prevX = x;
                break;
            }
        }
    }

    if (odd == 0.5f) for (float x = radius - odd; x >= -radius; x -= 1f) list.Add(new Vector2(x, 0f));
    return list;
}
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?