PointsOnShape and PointsInShape formula need some tweak

Hi guys, i have an assignment that requires me to find the coordinates in and on a shape itself, so assuming the shape is a square of 4 spaces. I found this formula somewhere but it was said to only work on floats, so after some tweaking, it does work but not fully functional.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//x y coordinates of a square
x, y
1, 1
1, 3
3, 3
3, 1

bool Shape::inPoly(int x,int y) 
{
    xArray[0] = 1;
    xArray[1] = 1;
    xArray[2] = 3;
    xArray[3] = 3;

    yArray[0] = 1;
    yArray[1] = 3;
    yArray[2] = 3;
    yArray[3] = 1;

    int i; 
    int j; 
    int nvert = 4;
    int c = 0;
    int testval = 0;

    for (i = 0, j = nvert - 1; i < nvert; j = i++) 
    {
        if ((yArray[i]>y) != (yArray[j]>y)) 
        {
            testval = (xArray[j]-xArray[i]) * (y-yArray[i]) / (yArray[j]-yArray[i]) + xArray[i];
        }
        if (x == testval) 
        {
            // point is on boundary!
            c = 0; // set indicator to "not inside"
            break; // abort loop
        }
        if (x < testval)
        {
            // intersection found
            c = !c;
        }
    }
   return c;
}

void Shape::pointInShape() 
{
    std::cout << "results" << std::endl;
    std::cout << inPoly(1,1) << std::endl;
    std::cout << inPoly(1,2) << std::endl;
    std::cout << inPoly(1,3) << std::endl;
    std::cout << inPoly(2,1) << std::endl;
    std::cout << inPoly(2,2) << std::endl;
    std::cout << inPoly(2,3) << std::endl;
    std::cout << inPoly(3,1) << std::endl;
    std::cout << inPoly(3,2) << std::endl;
    std::cout << inPoly(3,3) << std::endl;
}


Here are the results

1
2
3
4
5
6
7
8
9
0 <-- (means that 1,1 is not within polygon)
0 <-- (means that 1,2 is not within polygon)
0 <-- (means that 1,3 is not within polygon)
1 <-- (2,1 is is within polygon)// this should be 0
1 <-- (2,2 is is within polygon)
0 <-- (means that 2,3 is is not within polygon)
0 <-- (means that 3,1 is is not within polygon)
0 <-- (means that 3,2 is is not within polygon)
0 <-- (means that 3,3 is is not within polygon)


I should have only 1 1s, and 7 0s
Last edited on
bump
Topic archived. No new replies allowed.