Pages

Saturday, August 3, 2013

Touch Detection inside Polygon Shape xCode

Suppose you have some polygon shape like the above pic and you need to find the touch inside this shape.

For this i have made my own logic from various sources and this code is as below


-(BOOL)pointInPolygon:(int)xPos andY:(int) yPos andPolyArray:(NSArray *)poly
{
    int j = poly.count - 1;
    BOOL oddNodes = false;
    for (int i = 0; i <poly.count; i++) {
        NSValue *val = [poly objectAtIndex:i];
        CGPoint pi = [val CGPointValue];
        
        val = [poly objectAtIndex:j];
        CGPoint pj = [val CGPointValue];
        
        if ((pi.y < yPos && pj.y >= yPos) ||  (pj.y < yPos && pi.y >= yPos)) {
            if (pi.x + (yPos - pi.y) / (pj.y - pi.y) * (pj.x - pi.x) <xPos) {
                oddNodes = !oddNodes;
            }
        }
        j = i;
    }
    return oddNodes;
}

In this function you just need to pass X and Y position of Touch location, with the polygon co-ordinates Array.

Now how to create a Polygon Shape Array?

Here is the solution of this, to define a Polygon Shape points

self.trackArea = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(412,0)],
                  [NSValue valueWithCGPoint:CGPointMake(827,0)],
                  [NSValue valueWithCGPoint:CGPointMake(210,768)],
                  [NSValue valueWithCGPoint:CGPointMake(0,768)],
                  [NSValue valueWithCGPoint:CGPointMake(0,513)],
                  
                  nil];


Now How to call, So here is that

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    if([self pointInPolygon:touchPoint.x andY:touchPoint.y andPolyArray:self.track1Area])
    {
        NSLog(@"Touch Detected for polygon");
    }
}