2013-02-10 81 views
0

當談到Objective-C時,我是一個新手,所以請讓你的答案儘可能簡單。使NSTimer的時間間隔越來越短

這裏是在Xcode 4.5中製作的Pong遊戲的m文件。在方法viewDidLoad是一個計時器。我的問題是改變時間間隔(現在float gap = 0.05),所以球越來越快。我想我必須在別的地方製作一個新的計時器,而不是將重複設置爲YES。但我不知道該把它放在哪裏以及如何處理浮動間隙。

希望你明白我的意思。

PongOne.m:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:touch.view]; 
    paddle.center = CGPointMake(location.x, paddle.center.y); 
} 
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [self touchesBegan:touches withEvent:event]; 
} 
-(void)CPU { 
    ball.center = CGPointMake(ball.center.x + xgain, ball.center.y + ygain); 
    if (ball.center.x < 15) 
     xgain = abs(xgain); 

    if (ball.center.y < 15) 
     ygain = abs(ygain); 
     gap = gap + 0.01; 

    if (ball.center.x > 305) 
     xgain = -abs(xgain); 

    if (ball.center.y > 445){ 
     score++; 
     if (score <= 2){ 
      ball.center = CGPointMake(100, 100); 
      label1.text = [NSString stringWithFormat:@"%d", score]; 
     } else { 
      [timer invalidate]; 
      timer = nil; 
      [self performSegueWithIdentifier:@"byta1" sender:self]; 
     } 
    } 
    if (CGRectIntersectsRect(ball.frame, paddle.frame)) 
     ygain = -abs(ygain); 
    if (CGRectIntersectsRect(ball.frame, paddle2.frame)) 
     ygain = abs(ygain); 
    paddle2.center = CGPointMake(ball.center.x, paddle2.center.y); 
} 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    timer = [NSTimer scheduledTimerWithTimeInterval:gap target: self selector:@selector(CPU)   userInfo:nil repeats:YES]; 
    xgain = 10; 
    ygain = 10; 
} 
+0

當你試圖做你說你認爲你需要做的事情時發生了什麼? – 2013-02-10 22:30:44

+0

你的意思是在別的地方添加一個新的計時器? – user2059738 2013-02-10 22:34:04

+0

你真的想讓計時器本身加快嗎?當然你想增加球的速度。你可以在不改變定時器週期的情況下做到這一點例如,乘以xgain和ygain一些不同的因素。 – occulus 2013-02-10 22:43:41

回答

2

你可以僅僅刪除使用[timer invalidate]當你想改變它,使一個新的像你在viewDidLoad做你當前的計時器。或者,不要重複,然後在CPU中創建一個新的每一幀,無論當前的時間間隔是多少。無論如何,我不會推薦NSTimer用於任何類型的運行循環。另外,我認爲改變整個運行循環的時間以改變一個對象的速度是一個壞主意。相反,你應該改變你移動它的每一幀。爲什麼不自己改變{x,y}Gain

+0

謝謝!改變x,ygain解決了它! – user2059738 2013-02-10 22:57:12

+0

@ user2059738太好了!如果可以,請單擊左側的複選標記以接受此答案,以便其他人知道它已解決。 – Metabble 2013-02-10 22:59:24