Search code examples
iosuibuttonintnstimer

int seems to be resetting falling buttons in simple game


i am still pretty new this and i am trying to keep it as simple as possible.

this game has 2 astroids(buttons) falling from the top of the screen to the bottom using an nstimer and a cgpointmake. if you click an astroid there is a label on the screen that adds one point to your score, and the astroid goes back to the top to fall again.

the problem i am having is if i click an astroid they both go to the top and reset at the same time?

ive narrowd it down to what i think the problem is that it has something to do with the int that updates the score label every time the astroid is clicked

any help at all would be so helpful, i have looked all over the internet to find no help. thank you

  • the integer is point

  • the first astroid button is astroid1

  • the second astroid button is astroid2

  • the nstimer is astroidsfall

here is the view controller.h

#import <UIKit/UIKit.h>

int point;

@interface ViewController : UIViewController  {

IBOutlet UIButton *astroid1;
IBOutlet UIButton *astroid2;
IBOutlet UILabel *pointlabel;

NSTimer *astroidsfall;

}

-(IBAction)astroidone:(id)sender;
-(IBAction)astroidtwo:(id)sender;
-(IBAction)start:(id)sender;


@end

and here is the viewcontroller.m

@implementation ViewController

-(IBAction)start:(id)sender {
    astroidsfall = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self   selector:@selector(astroidphysics) userInfo:nil repeats:YES];
}

-(void)astroidphysics {
    astroid1.center = CGPointMake(astroid1.center.x, astroid1.center.y + 1);
    astroid2.center = CGPointMake(astroid2.center.x, astroid2.center.y + 1);
}

-(IBAction)astroidone:(id)sender {
    astroid1.center = CGPointMake(astroid1.center.x, astroid1.center.y - 300);

    point += 1;
    pointlabel.text = [NSString stringWithFormat:@"%i", point];
}

Solution

  • If you haven't turned off auto layout, then that's the problem. You shouldn't set any frames when using auto layout. You should make an IBOutlet to a constraint between your button and the top of the screen, and modify its constant value in code to move the button.