检测触摸了SKSpriteNode的哪个实例?

时间:2014-03-09 15:58:26

标签: sprite-kit touchesbegan skspritenode

我正在使用此代码检测并查看用户是否在我的SKSpriteNode框架内,如果是,请从屏幕中删除该节点。但我只希望被挖掘的节点消失。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */

    for (UITouch *touch in touches) {
            CGPoint location = [touch locationInNode:self];

        if ((location.x > self.crate.frame.origin.x && location.x < self.crate.frame.origin.x + self.crate.frame.size.width) &&
            (location.y > self.crate.frame.origin.y && location.y < self.crate.frame.origin.y + self.crate.frame.size.height)) {

            [self.crate removeFromParent];
        }
    }
}

在我的update方法中,我调用一个方法addCrate:每秒生成一个节点。

- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {

    self.lastSpawnTimeInterval += timeSinceLast;
    if (self.lastSpawnTimeInterval > 1) {
        self.lastSpawnTimeInterval = 0;
        [self addCrate];
    }
}

- (void)update:(NSTimeInterval)currentTime {
    // Handle time delta.
    // If we drop below 60fps, we still want everything to move the same distance.
    CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
    self.lastUpdateTimeInterval = currentTime;
    if (timeSinceLast > 1) { // more than a second since last update
        timeSinceLast = 1.0 / 60.0;
        self.lastUpdateTimeInterval = currentTime;
    }

    [self updateWithTimeSinceLastUpdate:timeSinceLast];

}

这是它正在调用的方法。

- (void)addCrate {

    // Create sprite
        self.crate = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:CGSizeMake(30, 30)];
        //self.crate.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.crate.frame.size];

    // Determine where to spawn the crate along the X axis
        int minX = self.crate.size.width / 2;
        int maxX = self.frame.size.width - self.crate.size.width / 2;
        int rangeX = maxX - minX;
        int actualX = (arc4random_uniform(rangeX)) + minX;

    // Create the crate slightly off-screen along the top,
    // and along a random position along the X axis as calculated above
        self.crate.position = CGPointMake(actualX, self.frame.size.height + self.crate.size.height/2);
        [self addChild:self.crate];
        self.crate.size = CGSizeMake(50, 50);


    // Determine speed of the crate
        int actualDuration = 3.5;

    // Create the actions
        SKAction * actionMove = [SKAction moveTo:CGPointMake(actualX, -self.crate.size.height/2) duration:actualDuration];
        SKAction * actionMoveDone = [SKAction removeFromParent];
        [self.crate runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}

但是当我在iPhone上运行时,有时只会注册水龙头并且屏幕上会移除该块,有时则不会。同样,我希望被点击的节点消失,只有那个节点。

谢谢!

U1

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
        [self addCrate];
    }
        return self;
}

- (void)addCrate {

    // Create sprite
        self.crate = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:CGSizeMake(30, 30)];
    self.crate.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(30, 30)];
        self.crate.userInteractionEnabled = YES;
        //self.crate.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.crate.frame.size];

    // Determine where to spawn the crate along the X axis
        int minX = self.crate.size.width / 2;
        int maxX = self.frame.size.width - self.crate.size.width / 2;
        int rangeX = maxX - minX;
        int actualX = (arc4random_uniform(rangeX)) + minX;

    // Create the crate slightly off-screen along the top,
    // and along a random position along the X axis as calculated above
        self.crate.position = CGPointMake(actualX, self.frame.size.height + self.crate.size.height/2);
        [self addChild:self.crate];
        self.crate.size = CGSizeMake(50, 50);


    // Determine speed of the crate
        int actualDuration = 3.5;

    // Create the actions
        SKAction * actionMove = [SKAction moveTo:CGPointMake(actualX, -self.crate.size.height/2) duration:actualDuration];
        SKAction * actionMoveDone = [SKAction removeFromParent];
        [self.crate runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];
    SKNode *touchedNode = [self nodeAtPoint:touchLocation];

    NSLog(@"touchLocation x: %f and y: %f", touchLocation.x, touchLocation.y);

    if (touchedNode != self) {
        NSLog(@"Removed from parent.");
        [touchedNode removeFromParent];
    }
}


- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {

    self.lastSpawnTimeInterval += timeSinceLast;
    if (self.lastSpawnTimeInterval > 1) {
        self.lastSpawnTimeInterval = 0;
        [self addCrate];
    }
}

- (void)update:(NSTimeInterval)currentTime {
    // Handle time delta.
    // If we drop below 60fps, we still want everything to move the same distance.
    CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
    self.lastUpdateTimeInterval = currentTime;
    if (timeSinceLast > 1) { // more than a second since last update
        timeSinceLast = 1.0 / 60.0;
        self.lastUpdateTimeInterval = currentTime;
    }

    [self updateWithTimeSinceLastUpdate:timeSinceLast];

}

1 个答案:

答案 0 :(得分:6)

我认为你应该在创建crate时使用设置node.name属性的组合,并在touchBegan:method中检查它们。

这样的事情:

SKSpriteNode *crate = [SKSpriteNode spriteNodeWithTexture:tex];
crate.name = @"crate";

和touchBegan:方法:

.....
if ([touchedNode.name isEquelToString:@"crate"]){
   // do something with that node
}
.....

<强> Upd1:

而不是写这些东西:

if ((location.x > self.crate.frame.origin.x && location.x < self.crate.frame.origin.x + self.crate.frame.size.width) &&
        (location.y > self.crate.frame.origin.y && location.y < self.crate.frame.origin.y + self.crate.frame.size.height)) {

        [self.crate removeFromParent];
    }

使用:

if(CGRectContainsPoint(self.frame, touchPoint)){
   // do something
}

<强> UPD2:

请勿在代码中看到您在包广告节点上设置了userInteractionEnabled = YES。

<强> Upd3:

以下是一个例子:

//
//  BGMyScene.m
//  Test1
//
//  Created by AndrewShmig on 3/10/14.
//  Copyright (c) 2014 Bleeding Games. All rights reserved.
//

#import "BGMyScene.h"

@implementation BGMyScene

- (id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */

        self.backgroundColor = [SKColor colorWithRed:0.15
                                               green:0.15
                                                blue:0.3
                                               alpha:1.0];

//      first label
        SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
//        myLabel.userInteractionEnabled = YES;
        myLabel.text = @"Hello, World!";
        myLabel.fontSize = 30;
        myLabel.position = CGPointMake(CGRectGetMidX(self.frame),
                                       CGRectGetMidY(self.frame));
        [self addChild:myLabel];

//      second label
        SKLabelNode *myLabel2 = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
//        myLabel2.userInteractionEnabled = YES;
        myLabel2.text = @"Hello, World!";
        myLabel2.fontSize = 30;
        myLabel2.position = CGPointMake(100, 100);
        [self addChild:myLabel2];
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];
    SKNode *touchedNode = [self nodeAtPoint:touchLocation];

    NSLog(@"touchLocation x: %f and y: %f", touchLocation.x, touchLocation.y);

    if (touchedNode != self) {
        NSLog(@"Removed from parent.");
        [touchedNode removeFromParent];
    }
}

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

@end

您将看到以下屏幕: enter image description here

点击&#34; Hello,World!&#34;标签将从父节点中删除。