SKScene 中的 UIPanGestureRecognizer [英] UIPanGestureRecognizer in SKScene

查看:19
本文介绍了SKScene 中的 UIPanGestureRecognizer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试验 UIGestureRecognizersSpriteKit 中的新 SKScene/SKNode's.我遇到了一个问题,我接近解决它,但我对一件事感到困惑.本质上,我有一个平移手势识别器,允许用户在屏幕上拖动精灵.

I've been experimenting with UIGestureRecognizers and the new SKScene/SKNode's in SpriteKit. I've had one problem, and I got close to fixing it but I am confused on one thing. Essentially, I have a pan gesture recognizer that allows the user to drag a sprite on the screen.

我遇到的唯一问题是实际初始化平移手势需要一次点击,然后只有在第二次点击时才能正常工作.我想这是因为我的平移手势是在 touchesBegan 中初始化的.但是,我不知道该放在哪里,因为在 SKScene 的 initWithSize 方法中对其进行初始化会使手势识别器无法实际工作.

The single problem I have is that it takes ONE tap to actually initialize the pan gesture, and then only on the SECOND tap on it works correctly. I'm thinking that this is because my pan gesture is initialized in touchesBegan. However, I don't know where else to put it since initializing it in the SKScene's initWithSize method stopped the gesture recognizer from actually working.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if (!self.pan) {

        self.pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(dragPlayer:)];
        self.pan.minimumNumberOfTouches = 1;
        self.pan.delegate = self;
        [self.view addGestureRecognizer:self.pan];
    }
}

-(void)dragPlayer: (UIPanGestureRecognizer *)gesture {

        CGPoint trans = [gesture translationInView:self.view];

        SKAction *moveAction =  [SKAction moveByX:trans.x y:-trans.y  duration:0];
        [self.player runAction:move];

        [gesture setTranslation:CGPointMake(0, 0) inView:self.view];
    }

推荐答案

那是因为你在 touches 开始时添加了手势,所以在至少点击屏幕一次之前,手势不存在.此外,我会验证您实际上是在使用 initWithSize: 作为您的初始化程序,因为在那里添加手势应该没有任何问题.

That's because you're adding the gesture in touches began, so the gesture doesn't exist until the screen has been tapped at least once. Additionally, I would verify that you're actually using initWithSize: as your initializer, because you shouldn't have any problems adding the gesture there.

另一个选项是移动代码以将手势添加到 -[SKScene didMovetoView:] 中,该代码在场景呈现后立即被调用.更多信息 在文档中.

Another option is to move the code to add the gesture into -[SKScene didMovetoView:] which gets called immediately after the scene has been presented. More info in the docs.

- (void)didMoveToView:(SKView *)view
{
    [super didMoveToView:view];
    // add gesture here!
}

这篇关于SKScene 中的 UIPanGestureRecognizer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆