Project/02 - Engine/LittleBigEngine/Math/HexUtils.cs
/// <summary>
/// Returns the hexagon containing a specified point in space
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
Returns the hexagon containing a specified point in space
Returns the hexagon containing a specified point in space
public static Hex VectorToHex(Vector2 v)
        {
            Hex hex = new Hex(0,0);
            float xRel = v.X / UStep.X;
            if (xRel > 0)
                xRel += 0.5f;
            else
                xRel -= 0.5f;
            float yOffset = UStep.Y * Math.Abs(hex.U % 2);
            float yRel = 0.5f * (v.Y - yOffset) / UStep.Y;
            if (yRel > 0)
                yRel += 0.5f;
            else
                yRel -= 0.5f;
            hex.U = (int)xRel;
            hex.V = (int)yRel;
            Vector2 offset = (v - hex.ToVector());
            offset.X = offset.X / 1;
            offset.Y = offset.Y / 2 * (float)Math.Cos(Math.PI / 6.0f);
            if (offset.X + offset.Y > 1)
                return new Hex(hex.U + 1, hex.V + Math.Abs(hex.U % 2));
            else if (offset.X - offset.Y > 1)
                return new Hex(hex.U + 1, hex.V - 1 + Math.Abs(hex.U % 2));
            else if (-offset.X + offset.Y > 1)
                return new Hex(hex.U - 1, hex.V + Math.Abs(hex.U % 2));
            else if (-offset.X - offset.Y > 1)
                return new Hex(hex.U - 1, hex.V - 1 + Math.Abs(hex.U % 2));
            else
                return hex;
        }
public static Hex VectorToHex ( Vector2 v ) { Hex hex = new Hex ( 0 , 0 ) ; float xRel = v . X / UStep . X ; if ( xRel > 0 ) xRel += 0.5f ; else xRel -= 0.5f ; float yOffset = UStep . Y * Math . Abs ( hex . U % 2 ) ; float yRel = 0.5f * ( v . Y - yOffset ) / UStep . Y ; if ( yRel > 0 ) yRel += 0.5f ; else yRel -= 0.5f ; hex . U = ( int ) xRel ; hex . V = ( int ) yRel ; Vector2 offset = ( v - hex . ToVector ( ) ) ; offset . X = offset . X / 1 ; offset . Y = offset . Y / 2 * ( float ) Math . Cos ( Math . PI / 6.0f ) ; if ( offset . X + offset . Y > 1 ) return new Hex ( hex . U + 1 , hex . V + Math . Abs ( hex . U % 2 ) ) ; else if ( offset . X - offset . Y > 1 ) return new Hex ( hex . U + 1 , hex . V - 1 + Math . Abs ( hex . U % 2 ) ) ; else if ( - offset . X + offset . Y > 1 ) return new Hex ( hex . U - 1 , hex . V + Math . Abs ( hex . U % 2 ) ) ; else if ( - offset . X - offset . Y > 1 ) return new Hex ( hex . U - 1 , hex . V - 1 + Math . Abs ( hex . U % 2 ) ) ; else return hex ; }
Returns the hexagon containing a specified point in space
Returns the hexagon containing a specified point in space
//First, find approximate U and V coordinates using uStep and vStep //The approximate UV can be wrong if the point lie on a corner of the unit square centered around the hex center //We test the 4 different edge cases
None
v
Vector2
None