Search code examples
sprite-kittouchesbegan

How to set the location of a tap


I want to set this game up so that when the user taps a specific point on the screen it dispenses a SKSpriteNode from the location. So what I've set up is this inside the touches began method:

for (UITouch *touch in touches) {
    score = score + 1;

    cat = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"cat.png"] size:CGSizeMake(35, 35)];
    cat.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)+120);

    [self addChild:cat];
}

Which works fine and adds the node to any where the touch occurred.

I want it only to be added when the user touches a specific location, so I tried setting this up:

for (touch locationInNode:CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)) {
    score = score + 1;

    cat = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"cat.png"] size:CGSizeMake(35, 35)];
    cat.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)+120);

    [self addChild:cat];
}

But it didn't work and told me I needed a square bracket ] for some reason.

How can I set it up so it only spawns if the user touches the middle of the screen?


Solution

  • I think you can use

    -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
            UITouch* touch = [touches anyObject];
            CGPoint positionInScene = [touch locationInNode:self];
            // Add your logic to check the specific location 
            // if( CGPointEqualToPoint (positionInScene, yourSpecificPosition)
    
            // Render Cat
    
    
      }
    

    Hope it will help