簡體   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