How to understand whether a point is included in a square?

  • 0
    How to understand whether a given point of coordinates (x, y) is included in the square (each point is floating)?
    JavaScript Anonymous, Oct 5, 2019

  • 2 Answers
  • 0
    const point = (x, y) => ({ x, y });

    const A = point(-1, 1);
    const B = point(1, 1);
    const C = point(1, -1);
    const D = point(-1, -1);
    const E = point(0, 0);

    const side = (a, b, p) => Math.sign((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x));

    const inArea = side(A, B, E) === -1 &&
    side(B, C, E) === -1 &&
    side(C, D, E) === -1 &&
    side(D, A, E) === -1;

    console.log(inArea); // true




    In Lua


    function point(x, y)
    return { ["x"] = x, ["y"] = y }
    end

    function sign(number)
    if (number < 0) then
    return -1
    elseif (number > 0) then
    return 1
    else
    return number
    end
    end

    function side(a, b, p)
    return sign((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x))
    end

    A = point(-1, 1)
    B = point(1, 1)
    C = point(1, -1)
    D = point(-1, -1)
    E = point(0, 0)

    inArea = side(A, B, E) == -1 and
    side(B, C, E) == -1 and
    side(C, D, E) == -1 and
    side(D, A, E) == -1;

    print(inArea) -- true

    Anonymous

  • 0
    If it is an even square, then x1 = x4, and the other parameters are also equal in pairs. In this case, write normally.

    For an even square - you need to make sure that the X-coordinate of the point is between the X-coordinates of the left and right borders; and similarly for the Y-coordinate.

    And you can calculate the midpoint. And then make sure that the deviation of the X and Y coordinates differs from the midpoint by no more than half the side of the square - in absolute value. The good thing is that you can not be afraid to confuse the right and left sides of the square.



    Or square m. rotated - then it should be set a little differently, there are several options.

    The calculations are a little more complicated here.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!