Search code examples
iosobjective-csprite-kitskscene

How to allow touching only in specific area in the scene?


I want to set touching to be only in part of the screen i have tried to add node layer in the part of the screen that not allowed to be touched and disable the user interactions

_mainLayer.userInteractionEnabled = NO;

but it didnt work any idea how to do it ?


Solution

  • Here's an example of how you can limit touch events to specific regions:

    Swift

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        for touch in (touches as! Set<UITouch>) {
            let location = touch.locationInNode(self)
    
            switch (location) {
            case let point where CGRectContainsPoint(rect, point):
                // Touch is inside of a rect
                ...
            case let point where CGPathContainsPoint(path, nil, point, false):
                // Touch is inside of an arbitrary shape
                ...
            default:
                // Ignore all other touches
                break
            }
        }
    }
    

    Obj-C

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        for (UITouch *touch in touches) {
            CGPoint location = [touch locationInNode:self];
    
            if (CGRectContainsPoint(rect, location)) {
    
            }
            else if (CGPathContainsPoint(path, nil, location, false)) {
    
            }
        }
    }