Is a point inside regular hexagon

前端 未结 8 1691
心在旅途
心在旅途 2020-12-31 08:59

I\'m looking for advice on the best way to proceed. I\'m trying to find whether a given point A:(a, b) is inside a regular hexagon, defined with center O:(x, y) and diameter

8条回答
  •  醉话见心
    2020-12-31 09:22

    This is what I have been using:

    public bool InsideHexagon(float x, float y)
    {
        // Check length (squared) against inner and outer radius
        float l2 = x * x + y * y;
        if (l2 > 1.0f) return false;
        if (l2 < 0.75f) return true; // (sqrt(3)/2)^2 = 3/4
    
        // Check against borders
        float px = x * 1.15470053838f; // 2/sqrt(3)
        if (px > 1.0f || px < -1.0f) return false;
    
        float py = 0.5f * px + y;
        if (py > 1.0f || py < -1.0f) return false;
    
        if (px - py > 1.0f || px - py < -1.0f) return false;
    
        return true;
    }
    

    px and py are the coordinates of x and y projected onto a coordinate system where it is much easier to check the boundaries.

    enter image description here

提交回复
热议问题