creating buttons in skview to point to different scenes

笑着哭i 提交于 2019-12-07 19:18:26

You should only assign the node once in - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event and then check which node it is, based on its name:

- (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:@"button"]) {
        [self runButtonActionOnNode:node];
    }
    else if ([node.name isEqualToString:@"button1"]) {
        [self runButtonActionOnNode:node];
    }
    else if  ([node.name isEqualToString:@"button2"]) {
         [self runButtonActionOnNode:node];
    }
    else if ([node.name isEqualToString:@"button3"]) {
         [self runButtonActionOnNode:node];
    }
}

I've also put your action code into a method, to cut down on duplication:

-(void)runButtonActionOnNode:(SKNode*) node{
    node.name = nil;
    SKAction *moveUp = [SKAction moveByX: 0 y: 100.0 duration: 0.5];
    SKAction *zoom = [SKAction scaleTo: 2.0 duration: 0.25];
    SKAction *pause = [SKAction waitForDuration: 0.5];
    SKAction *fadeAway = [SKAction fadeOutWithDuration: 0.25];
    SKAction *remove = [SKAction removeFromParent];
    SKAction *moveSequence = [SKAction sequence:@[moveUp, zoom, pause, fadeAway, remove]];
    [node runAction: moveSequence completion:^{
         SKScene *spaceshipScene  = [[MyScene alloc] initWithSize:self.size];
         SKTransition *doors = [SKTransition doorsOpenVerticalWithDuration:0.5];
         [self.view presentScene:spaceshipScene transition:doors];
    }];
}
Andrew97p

I wrote an answer creating a class specific for being used as buttons. It is available here and allows you to set images for the selected and normal states of the button, as well as the methods to be called for touch up inside events and touch down inside events. I think it will be easier for you to create your buttons as instances of this class, and then assign the part the moves to a new scene inside separate methods and set them as the actions called for the events. You don't even have to mess with touchesBegan when you use this class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!