How to detect UIImageView Collisions
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
?
精彩评论