0
votes

i'm trying to use SKLabelNode as menu buttons in my game

i have 4 buttons up left, up right, down left, down right

i give them name so i can catch the nodes in touch began but if i change the name of the label to something else it just don't work and do both action instead of doing the action for the new name

here's an example of the code :

init :

    buttonUpLeft.name = @"UpLeft";
    buttonUpRight.name = @"UpRight";
    buttonDownLeft.name = @"DownLeft";
    buttonDownRight.name = @"DownRight";

touchBegan :

UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKLabelNode *node = (SKLabelNode*) [self nodeAtPoint:location];


if ([node.name isEqualToString:@"DownLeft"]) {

        ...
        buttonUpLeft.name = @"Attack";
        buttonUpRight.name = @"Cry";
        buttonDownLeft.name = @"Execution";
        buttonDownRight.name = @"Back";
        ...
}

if ([node.name isEqualToString:@"Back"]) {

    ...
    buttonUpLeft.name=@"UpLeft";
    buttonUpRight.name=@"UpRight";
    buttonDownLeft.name=@"DownLeft";
    buttonDownRight.name=@"DownRight";
    ...
}

if ([node.name isEqualToString:@"Attack"]) {
    ...
}

if ([node.name isEqualToString:@"Cry"]) {   
    ...
}

if ([node.name isEqualToString:@"Execution"]) {
    ...
}

if ([node.name isEqualToString:@"DownRight"]) {
    ...
} 

but if i clic on "execution" or "downleft" it launch at the same time and same goes for "back" and "downright"

any idea to avoid this ?

1

1 Answers

0
votes

Most likely a problem with how you construct the if blocks.

For instance if the "DownLeft" button is pressed it will perform both the DownLeft and the Execution block because after DownLeft has been handled its name will be "Execution", thus running both if blocks with the same touch:

if ([node.name isEqualToString:@"DownLeft"]) {

        ...
        buttonDownLeft.name = @"Execution";
        ...
}

if ([node.name isEqualToString:@"Execution"]) {
    ...
}

Note that node and buttonDownLeft are pointing to the same node.

What you should do is use if / else if like so throughout the entire button touch handling blocks:

if ([node.name isEqualToString:@"DownLeft"]) {

        ...
        buttonDownLeft.name = @"Execution";
        ...
}
else if ([node.name isEqualToString:@"Execution"]) {
    ...
}

Also read up on how to set breakpoints and step through the code, things like that are very easy to analyze with the debugger.