OGeek|极客世界-中国程序员成长平台

标题: iOS 如何为 Sprite Kit 中的节点实现 UIButton 的类似行为? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 17:12
标题: iOS 如何为 Sprite Kit 中的节点实现 UIButton 的类似行为?

我希望我的一些 Sprite Kit 节点表现得像 UIButtons。我尝试了两种方法:

1) 使用 touchesBegan: - 如果用户很小心,这会起作用,但似乎会触发多次,比我禁用交互的速度要快,导致按钮能够被多次激活:

   spriteNode.userInteractionEnabled = YES;

//causes the following to fire when node receives touch
    -(void)touchesBeganNSSet *)touches withEventUIEvent *)event {

        self.userInteractionEnabled = NO;

        DLog(@"Do node action");
        self.userInteractionEnabled = YES;


    }

2)我切换到 Kobold-Kit作为 iOS Sprite Kit 之上的一个层。它允许我做的一件事是添加 button - like behavior到任何节点。但是,我遇到了一个问题,如果我有 2 个按钮堆叠在一起,点击顶部按钮会同时激活这两个按钮。在这种情况下, bool 标志可以防止重复交互。我在 KKScene 中跟踪了堆叠按钮一起触发此调用的问题:

-(void) touchesBeganNSSet *)touches withEventUIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    for (id observer in _inputObservers)
    {
        if ([observer respondsToSelectorselector(touchesBegan:withEvent])
        {
            [observer touchesBegan:touches withEvent:event];
        }
    }
}

场景只是向场景中的所有节点发送通知。这会导致堆叠在一起的按钮行为一起触发。

有没有一种方法或示例显示如何正确排列 Sprite 节点以允许类似于 UIButton 的行为,我只能激活顶部按钮,并且每次激活都会短暂禁用按钮之后的时间?



Best Answer-推荐答案


@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;

self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self actionselector(tapGestureStateChanged];
self.tapGesture.delegate = self;
[self.view addGestureRecognizer:self.tapGesture];


- (BOOL)gestureRecognizerShouldBeginUIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == self.tapGesture) {
        return CGRectContainsPoint(self.neededSprite.frame, [self convertPoint:[sender locationInView:self.view] toNode:self]);
    }
    return YES;
}



 - (void)tapGestureStateChangedUITapGestureRecognizer *)sender
    {
        if (sender.state == UIGestureRecognizerStateRecognized) {
/* do stuff here */
    }
    }

关于iOS 如何为 Sprite Kit 中的节点实现 UIButton 的类似行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640412/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4