繁体   English   中英

触摸屏时的“方法”

[英]Method 'while' touching screen

我正在使用iOS的Xcode制作游戏。 这是一段代码,当点击屏幕时,精灵会跳起来:

//tap/touch to jump (& play sound)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event{
       [self playSound];
       jumpUp = 16;
}

我如何实现它,以使Sprite在您触摸屏幕时不断上升,而不仅仅是单击?

//Pseudo code:
while touchingScreen {
    jumpUp +=1;
}

您需要在touchesBegan中开始某种循环,并在持续触摸时开始运行。 然后在touchesEnded (并取消!)中使该循环停止。 您可以使用重复的NSTimer或类似以下的内容。 您可能需要进行一些调整,以使其对于游戏足够平滑。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    // touching is a BOOL that keeps track of the touch event
    // YES means that a touch is happening at the moment
    touching = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSelector:@selector(up) withObject:nil afterDelay:.0];
    });
}

- (void)up {
    // move your sprite further up
    NSLog(@"up");
    if (touching) {
        // if the user is still touching repeat moving the sprite up
        [self performSelector:@selector(up) withObject:nil afterDelay:0.1];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    // The finger was lifted, stop the up movement
    touching = NO;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    touching = NO;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM