Last night, while learning new things, I started a little game from scratch. It is a simple ship that moves left and right via 2 UIButtons at the bottom of the screen and rocks that fall from the top that you avoid by shooting at them.
Everything worked well using NSTimer and the screen updated and UIbuttons functioned. But the more objects that moved on screen the slower it ran. I read threads today about getting away from NSTimer and using while loops. But while my game loops no buttons work or the screen wont refresh. I can hear the sounds running and the collision sound when a rock hits the ship.
I do understand that in the main thread, control is is transfered to the While loop and nothing else will work like buttons and screen redraw until control is released. I attempted to insert a [self performSelector.... waitUntilDone:YES] in the loop. After reading about this method it seems that it will break away from the while loop to perform a task and then return control again to the while loop. I have that line of code call a method that should update the screen [self.view setNeedDisplay];
But nothing is updating and the screen it's frozen, what am I missing to break away from the while loop to update / redraw the screen with the new object positions?
Everything worked well using NSTimer and the screen updated and UIbuttons functioned. But the more objects that moved on screen the slower it ran. I read threads today about getting away from NSTimer and using while loops. But while my game loops no buttons work or the screen wont refresh. I can hear the sounds running and the collision sound when a rock hits the ship.
Code:
-(void)viewDidAppear:(BOOL)animated{
[self addRock];
while (game_is_running)
{
[self runLoop];
}
}
-(void)runLoop{
[self shipMove]; // Uses UIButtons to move left and right.
[self moveShotPosition]; //Moves the shot int eh y direction
[self moveRockPostion]; //moves the rock in the y direction down
[self checkCollision]; // checks for collision of rock and ship or shot and rock
if (!music.playing && lives > 0) { // If music stops, restart it.
[music play];
}
[self performSelectorOnMainThread:@selector(updateTheView) withObject:nil waitUntilDone:YES];
}
-(void)updateTheView{
[self.view setNeedsDisplay];
}
I do understand that in the main thread, control is is transfered to the While loop and nothing else will work like buttons and screen redraw until control is released. I attempted to insert a [self performSelector.... waitUntilDone:YES] in the loop. After reading about this method it seems that it will break away from the while loop to perform a task and then return control again to the while loop. I have that line of code call a method that should update the screen [self.view setNeedDisplay];
But nothing is updating and the screen it's frozen, what am I missing to break away from the while loop to update / redraw the screen with the new object positions?