简体   繁体   中英

collision of two images problem

Here is my code:

-(void)collision {
    if(CGRectIntersectsRect(ball.frame,center.frame)) {
        center.alpha=0.1;
    }
}

-(void)viewDidLoad {
    [super viewDidLoad];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:7.0f];
    [ball setCenter:CGPointMake(200, 100)];
    [UIView commitAnimations];
    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(collision) userInfo:nil repeats:YES];
}

My problem is that when viewDidLoad "center.alpha=0.1" but "center" and "ball" have not collided yet, I don't know why, I think it is due to the animation.

Although the animation takes 7 seconds, [ball setCenter:CGPointMake(200, 100)]; is set immediately and because of that - (void)collision probably sets your alpha to 0.1 before "ball" intersects with "center" in the animation.

Instead of UIView animations you could use a NSTimer to slowly change the center of "ball".

You are scheduling the call to collision 0.01 seconds after the line is executed at the end of viewDidLoad. But the view hasn't been displayed yet and so it could take longer than 0.01 seconds to display the view.

Try viewDidAppear

Having said that, I think you are not clear on the purpose of the animtions in iOS. These are not for calculating collision detection - they are just for moving things from a start point to an end point over a set time. I would suggest you read the Apple docs on the animation system.

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