UITouch坐标和SKSpriteNode坐标不同

时间:2015-02-24 20:52:17

标签: ios xcode sprite-kit

我有一个用图片初始化的SKSpriteNode。我使用-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event方法来确定用户触摸是否在精灵的范围内。出于某种原因,即使我在精灵内部点击,坐标甚至都不相似。他们似乎在不同的坐标系上。

#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

2 个答案:

答案 0 :(得分:1)

NodeView具有不同的坐标系。 如果您需要知道节点坐标中点击点的位置,您可能需要替换以下行:

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

by:

CGPoint touchLocation = [touch locationInNode:self];

答案 1 :(得分:0)

对于Swift 4及更高版本:

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