4

我正在构建一个基于精灵工具包的游戏,缺少“右键单击”确实很难向我的用户传达一些重要信息。作为解决方案,我正在考虑长按、两指轻敲等手势。

如何在 SKSpriteNode 上实现手势?

这是我目前用来在触摸 SKSpriteNode 时获得类似按钮的行为的方法。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self selectSkill:YES];
}
4

3 回答 3

2

之前UIGestureRecognizer,您保留状态变量来跟踪它们开始的位置和时间。这是一个快速的解决方案,其中buttonTouched:有一种方法可以检查 UITouch 是否在您正在检查的按钮上。

var touchStarted: NSTimeInterval?
let longTapTime: NSTimeInterval = 0.5

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if buttonTouched(touch) {
            touchStarted = touch.timestamp
        }
    }
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if buttonTouched(touch) && touchStarted != nil {
            let timeEnded = touch.timestamp
            if timeEnded - touchStarted! >= longTapTime {
                handleLongTap()
            } else {
                handleShortTap()
            }
        }
    }
    touchStarted = nil
}

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
    touchStarted = nil
}
于 2015-03-27T20:23:15.923 回答
1

这是一个很好的组件,可以帮助 https://github.com/buddingmonkey/SpriteKit-Components

于 2014-05-06T04:21:40.623 回答
0

没有简单的方法可以做到这一点,但我能想到的一种方法是将子 SKView 添加到您的 SKScene 并将 UIImageView 作为该 SKView 中唯一的东西。然后,您可以像往常一样向 SKView 添加手势识别器。

这是我正在谈论的一个例子:

UIImageView *button = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ButtonSprite"]];

SKView *spriteNodeButtonView = [[SKView alloc] initWithFrame:CGRectMake(100, 100, button.frame.size.width, button.frame.size.height)];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(someMethod:)];
[spriteNodeButtonView addGestureRecognizer:tap];

[spriteNodeButtonView addSubview:button];

您可以将 SKView 放在任何您想要的位置,并在 SKView 上使用任何手势识别器:UITapGestureRecognizerUILongPressGestureRecognizerUISwipeGestureRecognizerUIPinchGestureRecognizerUIRotationGestureRecognizerUIPanGestureRecognizerUIScreenEdgePanGestureRecognizer

然后为你的方法实现做这样的事情:

-(void)someMethod:(UITapGestureRecognizer *)recognizer {
    CGPoint touchLoc = [recognizer locationInView:self.view];
    NSLog(@"You tapped the button at - x: %f y: %f", touchLoc.x, touchLoc.y);
}
于 2013-12-14T20:01:19.733 回答