简体   繁体   中英

Square collision detection iPhone

I have this game where i need to know if the ball has hit a wall on the side (to bounce back on the x-axis) or on the top (to bounce back on the y-axis, like a bounce on the ground). They work fine individually, but when I uncomment both of them, it dosen't work. (I think this is because the code is 'overlapping'?). Anyway, here is the code, and any help is fantastic:

if (CGRectIntersectsRect(guy.frame, wall_01.frame)) {
            if (guy.frame.origin.y+guy.frame.size.height >= wall_01.frame.origin.y && guy.frame.origin.y <= wall_01.frame.origin.y+wall_01.frame.size.height) {
                iJump *= kRestitution;
            }
            if (guy.frame.origin.x+guy.frame.size.width >= wall_01.frame.origin.x && guy.frame.origin.x <= wall_01.frame.origin.x+wall_01.frame.size.width) {
                jJump *= kRestitution;
            }
        }

assuming wall is on the left side and the y increases from top to bottom

CGFloat leftWall = someXPosition;
CGFloat ground = someYPosition;


CGFloat ballLeft = CGRectGetMinX(guy.frame);
CGFloat ballRight = CGRectGetMaxX(guy.frame);
CGFloat ballBottom = CGRectGetMaxY(guy.frame);

if (ballLeft <= leftwall && ballBot >= ground){
   //ball hit corner ?

} else if (ballLeft <= leftWall){
   //passed or touched wall

} else if (ballBot >= ground){
   //passed or touched ground
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM