2

我试图运行 2 个 NSTimer。我注意到它不起作用。是否有可能运行 2 个 NSTimer?我试图在球移动时开始反击。但是如果我开始它,当计数器到达下一秒时,敌人的球会从头开始。当然,这场比赛还没有结束。

这是我的“项目”:

//.h
@interface ViewController : UIViewController {

    IBOutlet UIButton *startButton;
    NSTimer *randomMain;
    CGPoint pos; 
    IBOutlet UIImageView *enemy;
    IBOutlet UIImageView *player;

    IBOutlet UIButton *startCounter;

    IBOutlet UILabel *seconds;
    NSTimer *timer;
    int MainInt;
}

-(IBAction)start2:(id)sender;

- (IBAction)start;

//.m

@implementation ViewController

-(void)countup {
    MainInt += 1;
    seconds.text = [NSString stringWithFormat:@"%i", MainInt];
}

-(IBAction)start2:(id)sender {
    MainInt = 0;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup)userInfo:nil repeats:YES];   
}

- (IBAction)start {
    [startButton setHidden:YES];
    randomMain = [NSTimer scheduledTimerWithTimeInterval:(0.03) target:self selector: @selector(onTimer) userInfo:(nil) repeats:YES];
}

-(void)onTimer{   
    [self checkCollision];

    enemy.center = CGPointMake(enemy.center.x+pos.x,enemy.center.y+pos.y);

    if (enemy.center.x > 320 || enemy.center.x < 0)
        pos.x = -pos.x;
    if (enemy.center.y > 480 || enemy.center.y < 0)
        pos.y = -pos.y;
}

- (void)checkCollision {

    if( CGRectIntersectsRect(player.frame,enemy.frame))
    {
        [randomMain invalidate];
        [startButton setHidden:NO];

        CGRect frame = [player frame];
        frame.origin.x = 137.0f;
        frame.origin.y = 326.0;
        [player setFrame: frame];

        CGRect frame2 = [enemy frame];
        frame2.origin.x = 137.0f;
        frame2.origin.y = 20.0;
        [enemy setFrame: frame2];

       UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"You hit the ball!" message: [NSString stringWithFormat:@"Try it again!"] delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *myTouch = [[event allTouches] anyObject];
    player.center = [myTouch locationInView:self.view];    
}

-(void)viewDidLoad {   
    [super viewDidLoad];
    // X Speed Y Speed
    pos = CGPointMake(5.0,4.0);
}
4

1 回答 1

0

尝试在不同的线程中运行第二个计时器。即,将其写入在单独线程中运行的函数中。在设置第二个计时器的位置调用该函数。

于 2012-12-21T14:15:19.927 回答