对象中的UITouch方法无法正常工作

时间:2014-09-16 20:41:58

标签: ios sprite-kit

我有一个SKScene名称“Scene”,其中我实例化了SKNode的类“Button”子类的2个对象。 为了不增加我的SKScene中的代码行数,我想直接在我的班级“Button”中实现触摸方法。 这是代码:

Scene.h

#import <SpriteKit/SpriteKit.h>

@interface Scene : SKScene
@end

Scene.m

#import "Scene.h"
#import "Button.h"

@implementation Scene

- (id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        Button *button01 = [Button node];
        [button01.number setString: @"1"];
        button01.position = CGPointMake(CGRectGetMidX(self.frame) - 50, 160);

        Button *button02 = [Button node];
        [button02.number setString: @"2"];
        button02.position = CGPointMake(CGRectGetMidX(self.frame) + 50, 160);

        [self addChild:button01];
        [self addChild:button02];
    }

    return self;
}

@end

Button.h

#import <SpriteKit/SpriteKit.h>

@interface Button : SKNode

@property (strong, nonatomic) NSMutableString *number;

@end

Button.m

#import "Button.h"

SKShapeNode *button;

@implementation Button

- (id)init
{
    if (self = [super init])
    {
        self.userInteractionEnabled = YES;

        _number = [[NSMutableString alloc] init];
        [_number setString: @"0"];

        button = [SKShapeNode node];
        [button setPath:CGPathCreateWithRoundedRect(CGRectMake(-25, -25, 50, 50), 4, 4, nil)];
        button.fillColor = [SKColor clearColor];
        button.lineWidth = 1.0;
        button.strokeColor = [SKColor whiteColor];
        button.position = CGPointMake(0, 0);

            SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
            label.text = _number;
            label.fontSize = 20;
            label.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
            label.position = CGPointMake(0, 0);
            label.fontColor = [SKColor whiteColor];

            [button addChild:label];

        [self addChild:button];
    }
    return self;
}

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

    if(CGRectContainsPoint(button.frame, location))
    {
        button.fillColor = [SKColor whiteColor];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    button.fillColor = [SKColor clearColor];
}

@end

问题是当我触摸button01内部时,它会改变button02颜色。好像该动作仅适用于我班级的最后一个实例。 我怎么能解决这个问题。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

由于某些原因,您的ButtonSKNode作为超类。 SKNode没有size属性,您可以对其进行更改,因此它需要整个大小的父节点。将其视为场景的一层。因此,无论您何时触摸,最新的SKScene孩子(在您的情况下为button02)都会接触到。

解决方案:直接将Button定义为SKShapeNode的子类。

答案 1 :(得分:0)

问题是以下变量在Button类中具有全局范围:

SKShapeNode *button;

由于它在Button的实例之间共享,因此它包含对实例化的最后一个Button的SKShapeNode的引用。在这种情况下,按钮2.您可以通过将按钮定义为实例变量来解决此问题:

@implementation Button
{
    SKShapeNode *button;
}

...
相关问题