开发者

How to detect UIImageView Collisions

开发者 https://www.devze.com 2023-02-11 18:58 出处:网络
I am wondering why my code doesn\'t work. I want my ball (UIImageView) to bounce off of a block (also a UIImageView). My ball switches both the x and y movements to negative instead of just one. What

I am wondering why my code doesn't work. I want my ball (UIImageView) to bounce off of a block (also a UIImageView). My ball switches both the x and y movements to negative instead of just one. What is wrong??? Please Help... Here is my code

-(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) {
     开发者_StackOverflow社区   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;
    }
}


Does it happen even when the ball hits the center of an edge? Anyway don't you just need to handle one dimension at a time? Can't the third if be else if?

0

精彩评论

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