简体   繁体   中英

iphone development: collision detection does not work for the animation

The code below simply creates small squares from top of the screen and moves to the bottom. I also have an UIImageView(player) which is controlled by the accelerometer on the x axis. The aim is not touching the animated object. like a simple race game. Although I have no error I cant detect the collision. I could not find the mistake in my code. What can be the problem?

-(void)printOut:(NSTimer*)timer1;
{


    for (int i = 0; i < 100; i++) {

        p = arc4random_uniform(320)%4+1;

        CGRect startFrame = CGRectMake(p*50, -50, 50, 50);
        CGRect endFrame   = CGRectMake(p*50, CGRectGetHeight(self.view.bounds) + 50,
                                       50,
                                       50);

        animatedView = [[UIView alloc] initWithFrame:startFrame];
        animatedView.backgroundColor = [UIColor redColor];

        [self.view addSubview:animatedView];

        [UIView animateWithDuration:2.f
                              delay:i * 0.5f
                            options:UIViewAnimationCurveLinear
                         animations:^{animatedView.frame = endFrame;}
                         completion:^(BOOL finished) {[animatedView removeFromSuperview];}];


        CGRect movingFrame = [[animatedView.layer presentationLayer] frame];

        if(CGRectIntersectsRect(player.frame, movingFrame)){
            [timer invalidate];
            NSLog(@"asdad");

            UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"You Lost" message:[NSString stringWithFormat:@"You were hit!"] delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
            [alert show];
        }

    }

    [timer1 invalidate];

}

You cannot detect the collision because the only frame values the system is ever aware of for your animation are the beginning frame, and the end frame. So unless the object you are trying to detect collision of collides with the beginning or end frame of the first object, you need to find a different way to detect it. UIView animations were designed for aesthetics not game logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM