使NSTimer的间隔越来越短

时间:2013-02-10 22:27:16

标签: objective-c cocoa-touch nstimer

对于Objective-C,我是新手,所以请尽量让答案变得简单。

这是在Xcode 4.5中制作的Pong游戏的m文件。在方法viewDidLoad是一个计时器。我的问题是改变间隔(现在浮动间隙= 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;
}

1 个答案:

答案 0 :(得分:2)

您可以使用[timer invalidate]删除当前计时器,如果您想要更改它并像viewDidLoad那样制作新计时器。或者,使其不重复,然后在CPU每帧创建一个新的,无论当前的间隔应该是什么。无论如何,我不建议NSTimer用于任何类型的运行循环。另外,我想说改变整个运行循环的时间只是为了改变一个对象的速度是个坏主意。相反,你应该改变你每帧移动多少。为什么不自己更改{x,y}Gain