0

I was wondering if there was a more efficient way to changing the property of a SKSpriteNode in touchesBegan than my current method. The following is my method:

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

    if ([node.name isEqualToString:@"Start"]){
        for (SKSpriteNode *node2 in [self children]){
            if ([node2.name isEqualToString:@"Start"]){
                node2.texture = [SKTexture textureWithImageNamed:@"button_beige_pressed"];
                }
            }
    }
        ...
}
4
  • Why do you need to have if ([node.name isEqualToString:@"Start"]){ and then if ([node2.name isEqualToString:@"Start"]){ ?
    – El Tomato
    Nov 19, 2015 at 22:50
  • On a separate note, you must reuse textures as much as possible. The method textureWithImageNamed loads the textures which is an expensive operation. Maybe you can pre-load the texture and just apply it later.
    – mohkhan
    Nov 19, 2015 at 23:10
  • 1
    Can you create the SKTexture outside of the for loop (and then assign the node2.texture to that texture? Would that be a better way?
    – Gliderman
    Nov 20, 2015 at 1:17
  • I can't access/change the properties of the node with the name "Start" when I try it in the first for loop; that's because its a spritenode. That is why I must make another for loop that accesses the sprite nodes. I have made an edit: It was supposed to be SKNode *node = [self nodeAtPoint: location];
    – user5177178
    Nov 20, 2015 at 20:02

2 Answers 2

0

Your current logic suggest that you have multiple nodes with the name 'start'. If this is actually the case I suggest creating an array and storing all 'start' nodes in said array.

If however you only have a single node with the name 'start', then no loop is needed as you already have a reference to the node with the touch function.

0

I found a solution:

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

    if ([node.name isEqualToString:@"Start"]){
        node.texture = startPressed;
    }

}

I was using a Node when I should have been using a spritenode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy