chargerstriker
chargerstriker

Reputation: 496

UITouch coordinates and SKSpriteNode coordinates are different

I have an SKSpriteNode that is initialized with an image. I am using the -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event method to figure out if the user touch is within the bounds of the sprite. For some reason, even when I tap inside the sprite, the coordinates are not even similar. They seem to be on a different coordinate system.

#import "GameScene.h"

SKSpriteNode *card;

@implementation GameScene

-(void)didMoveToView:(SKView *)view {

        /* Setup your scene here */
        self.backgroundColor = [SKColor whiteColor];
        card = [SKSpriteNode spriteNodeWithImageNamed:@"card"];
        card.position = CGPointMake(500, 500);

    [self addChild:card];


}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    int cardX = card.frame.origin.x;
    int cardwidth = card.frame.size.width;
    int cardY = card.frame.origin.y;
    int cardHeight = card.frame.size.height;


    if(touchLocation.x >= card.frame.origin.x &&
       touchLocation.x <= (card.frame.origin.x + card.frame.size.width) &&
       touchLocation.y <= card.frame.origin.y &&
       touchLocation.y >= (card.frame.origin.y + card.frame.size.height))
    {
        self.backgroundColor = [SKColor blackColor];
    }
    else{
        self.backgroundColor = [SKColor whiteColor];
    }
}

@end

Upvotes: 2

Views: 125

Answers (2)

Alex
Alex

Reputation: 301

For Swift 4 and above:

if playButton.frame.contains(touch.location(in: scene!)) {
            print("Play button touched")
}

Upvotes: 0

KIDdAe
KIDdAe

Reputation: 2722

Node and View have different coordinate system. If you need to know the location of the tapped point in the node coordinate you may want to replace the line :

CGPoint touchLocation = [touch locationInView:self.view];

by :

CGPoint touchLocation = [touch locationInNode:self];

Upvotes: 2

Related Questions