我正在使用适用于iOS的Sprite Kit。 所以我有Sprite Kit的按钮类的这一部分:
#pragma Touch Events setup
- (void) setTouchDownAction:(SEL)action OnTarget:(id)target
{
touchDownTarget = target;
touchDownAction = action;
}
- (void) setTouchUpAction:(SEL)action OnTarget:(id)target
{
touchUpTarget = target;
touchUpAction = action;
}
#pragma Touch Handling
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInNode:self.parent];
if(CGRectContainsPoint(self.frame, touchPoint))
[self setSelected:YES];
if(touchDownTarget && touchDownAction && CGRectContainsPoint(self.frame, touchPoint))
{
objc_msgSend(touchDownTarget, touchDownAction);
}
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInNode:self.parent];
if(touchUpTarget && touchUpAction && CGRectContainsPoint(self.frame, touchPoint))
{
[self setSelected:NO];
objc_msgSend(touchUpTarget, touchUpAction);
}
}
我创建了这样一个类的对象:
SKButton *onePlayerButton = [[SKButton alloc] initWithTexture:menuButtonTexture selectedTexture:menuButtonSelectedTexture size:CGSizeMake(buttonWidth, buttonWidth / 6)];
onePlayerButton.position = CGPointMake(self.size.width / 2, self.size.height - 150);
onePlayerButton.color = [UIColor blueColor];
onePlayerButton.colorBlendFactor = 0.4;
[onePlayerButton setTitle:@"1 Player"];
[onePlayerButton setTouchUpAction:@selector(onePlayerButtonClicked) OnTarget:self];
[self addChild:onePlayerButton];
如果我创建同一个类的第二个对象并点击第二个或第一个按钮,则两个对象都会响应点击。
在场景中,我得到了这样的触摸事件:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[onePlayerButton touchesBegan:touches withEvent:event];
[multiplayerButton touchesBegan:touches withEvent:event];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[onePlayerButton touchesEnded:touches withEvent:event];
[multiplayerButton touchesEnded:touches withEvent:event];
}
为什么两个对象都会响应?
谢谢!
答案 0 :(得分:0)
问题在于,无论用户在哪里触摸,您都会同时向按钮发送触摸。
尝试为您的按钮添加名称,如下所示:
onePlayerButton.name = @"one_player";
multiplayerButton.name = @"mul_player";
现在在touchesBegan中仅在用户触摸按钮时添加事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:touchLocation];
if ([node.name isEqualToString:@"one_player"])
{
[onePlayerButton touchesBegan:touches withEvent:event];
}
else if ([node.name isEqualToString:@"mul_player"])
{
[multiplayerButton touchesBegan:touches withEvent:event];
}
}
这应该对你有用,已经过测试。
祝你好运!