如何检测UIImageView碰撞

时间:2011-02-18 20:45:28

标签: iphone xcode uiimageview collision-detection bounce

我想知道为什么我的代码不起作用。我希望我的球(UIImageView)从一个块(也是一个UIImageView)反弹。我的球将x和y运动切换为负值而不是仅为1。怎么了???请帮助......这是我的代码

-(void)animateBall:(NSTimer *)theTimer {

    collisionCount ++;
    bouncyBall.center = CGPointMake(bouncyBall.center.x + ballMovement.x, bouncyBall.center.y + ballMovement.y);

    if (CGRectIntersectsRect(bouncyBall.frame, wallOne.frame)) {
        if (collisionCount >= 5) {
            [self processCollision:wallOne];
            collisionCount = 0;
        }
    }

    if (bouncyBall.center.x > 313 || bouncyBall.center.x < 8) {
        ballMovement.x = -ballMovement.x;
    }
    if (bouncyBall.center.y > 453 || bouncyBall.center.y < 8) {
        ballMovement.y = -ballMovement.y;
    }
}

-(void)processCollision:(UIImageView *)wall {

    if (ballMovement.x > 0 && wall.frame.origin.x - bouncyBall.center.x <= 4) {
        ballMovement.x = -ballMovement.x;
    }
    else if (ballMovement.x < 0 && bouncyBall.center.x - (wall.frame.origin.x + wall.frame.size.width) <= 4) {
        ballMovement.x = -ballMovement.x;
    }

    if (ballMovement.y > 0 && wall.frame.origin.y - bouncyBall.center.y <= 4) {
        ballMovement.y = -ballMovement.y;
    }
    else if (ballMovement.y < 0 && bouncyBall.center.y - (wall.frame.origin.y + wall.frame.size.height) <= 4) {
        ballMovement.y = -ballMovement.y;
    }
}

1 个答案:

答案 0 :(得分:0)

即使球击中边缘的中心,也会发生这种情况吗?无论如何,你不是一次只需要处理一个维度吗?第三个if不能else if吗?