简体   繁体   English

触摸屏时的“方法”

[英]Method 'while' touching screen

I'm making a game using Xcode for iOS. 我正在使用iOS的Xcode制作游戏。 This is a segment of code I have that makes the sprite jump up when the screen is tapped: 这是一段代码,当点击屏幕时,精灵会跳起来:

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

How can I implement it so that the sprite just keeps going up whist you are touching the screen instead of just a single tap? 我如何实现它,以使Sprite在您触摸屏幕时不断上升,而不仅仅是单击?

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

You need to start some kind of loop in touchesBegan that runs while the touch is lasting. 您需要在touchesBegan中开始某种循环,并在持续触摸时开始运行。 Then in touchesEnded (and cancelled!) make that loop stop. 然后在touchesEnded (并取消!)中使该循环停止。 You can use a repeating NSTimer or something like the following. 您可以使用重复的NSTimer或类似以下的内容。 You may need to do some adjustments to make it smooth enough for a game. 您可能需要进行一些调整,以使其对于游戏足够平滑。

- (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