I’m a newbie when it comes to Objective-C so please make your answers as easy as posible.
Here is the m-file for a Pong-game made in Xcode 4.5. In the method viewDidLoad is a timer. My problem is to change the interval (now float gap = 0.05) so the ball goes faster and faster.. I guess I have to make a new timer somewhere else and not have the repeat set to YES. But i have no idea where to put it and what to do with the float gap.
Hope you understand what i mean.
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;
}
You can just remove your current timer using
[timer invalidate]when you want to change it and make a new one like you do in yourviewDidLoad. Or, make it not repeat, then inCPUcreate a new one every frame with whatever the current interval should be. Regardless, I wouldn’t recommendNSTimerfor any kind of run loop. Also, I’d say it’s a bad idea to alter the timing of your whole run loop just to change the speed of one object. Rather, you should alter how much you move it each frame instead. Why not change{x,y}Gainthemselves?