CGRect碰撞与多个CGRects

时间:2012-05-03 17:28:25

标签: iphone objective-c ios xcode cgrect

我是iPhone编程的新手,我目前正在开展ballsplit游戏。在这个游戏中,当我的子弹击中任何球时,我希望它创造两个新球。我的子弹和球都是uiimageview。

这是我的代码:

if ((CGRectIntersectsRect(bullet.frame,Ball.frame)) && !(ball)){
    ball=TRUE;
    x=Ball.frame.origin.x;
    y=Ball.frame.origin.y;
    [self performSelector:@selector(createball)];
}

这是我的创建球功能..

-(void)createball{
    if (ball) {
        imageMove1 = [[UIImageView alloc] initWithFrame:CGRectMake(x,y,50 ,50)];  
        UIImage *imag = [UIImage imageNamed:@"ball1.png"];
        [imageMove1 setImage:imag];
        [self.view addSubview:imageMove1];
        [ballArray addObject:imageMove1];

        imageMove2 = [[UIImageView alloc] initWithFrame:CGRectMake(x,y,50 ,50)]; 
        UIImage *imag1 = [UIImage imageNamed:@"ball1.png"];
        [imageMove2 setImage:imag1];
        [self.view addSubview:imageMove2];
        [ballArray addObject:imageMove2];
        ball=FALSE;
        [self performSelector:@selector(moveball)];
    }
}

现在,在创建了这两个uiimgeview之后,当子弹击中这两个uiimageview中的一个时,我希望它创建另外两个uiimageview。但是我面临的问题是如何才能获得这些新的uiimageview的帧...

1 个答案:

答案 0 :(得分:2)

移动子弹后,迭代通过数组存储对球图像的引用:

for (UIImageView *ball in ballArray){
     //check for collision
    if (CGRectIntersectsRect(bullet.frame,ball.frame)){
        //hit
    }
}

检查球之间的碰撞:

for (UIImageView *ballOne in ballArray){
    for (UIImageView *ballTwo in ballArray){
        //check for collision
        if (CGRectIntersectsRect(ballOne.frame,ballTwo.frame) && ballOne != ballTwo){
            //hit
        }
    }
}