开发者

Detect collision between multiple UIImageViews that are animated with the same name

I am trying to detect the collision between a falling/animated UIImageView that is created every second with an NSTimer. Here's the code:

-(void)newobject{

    int randomx = 76+ arc4random() %(290);
    int randomDuration = 2+ arc4random() %(6);
    int randomImage = 1+ arc4random() %(3) ;

    NewObject = [[UIImageView alloc] initWithFrame:CGRectMake(randomx,0,36 ,36)];        
    UIImage *imag = [UIImage imageNamed:@"ball.png"];
    [NewObject setImage:imag];
    [self.view addSubview:NewObject];

    numberofObjects += 1;
    NewObject.tag = numberofObjects;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:randomDuration];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDone:finished:context:)];
    NewObject.frame = CGRectMake(randomx, 300,NewObject.frame.size.width,NewObject.frame.size.height);

    [UIView commitAnimations];
}

That code crates a new UIImageView with the name NewObject and animates it down the screen. To detect the collision I have another NSTimer that is called every 1.0/60. Here's the code:

-(void)Collison{

    for (int i = 1; i < numberofObjects; i++) {
      开发者_运维百科  UIImageView *image = NewObject;

        [image viewWithTag:i];
        CALayer *layer = image.layer.presentationLayer;
        CGRect NewObjectFrame =  layer.frame;
        CALayer *layer2 = Sprint.layer.presentationLayer;
        CGRect SprintFrame = layer2.frame;

        if (CGRectIntersectsRect(NewObjectFrame, SprintFrame)) {
            [self StopTimers];

            NSLog(@"hello");
        }
    }
}

The problem is that the console says "It works" but the UIImage didn't collide and I can collide the character with the image but the console says nothing and at the same time if I try to collide the character with the UIImageView it works. What i'am trying to say is that it's not reliable. Can someone help?

update: I edited the code but now it detecting the last uiimageview that is added.


ok well i got it. It's simple so all you need to do is make an NSMutableArray and check the array for collision with a for loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜