Why Do Objects Overlap with CGRectIntersectsRect?

280 Views Asked by At

I am creating a puzzle game for which you have to move an object around obstacles in order to reach your target. However, for some reason objects are overlapping when I use CGRectIntersectsRect. I want the objects to STOP when they touch edges with each other, NOT when they're overlapping each other. Current code is as follows:

-(void)objectObstacleCollision {

if (CGRectIntersectsRect(object.frame, obstacle1.frame)) {
    xMotion = 0;
    yMotion = 0;

    if (objectMovingUp == YES) {
        objectCrashedUp = YES;
        objectMovingUp = NO;

        if (objectCrashedUp == YES && objectMovingUp == NO) {

            up.hidden = YES;
            down.hidden = NO;
            right.hidden = NO;
            left.hidden = NO;
        }
    }

This is causing objects to overlap upon impact which causes problems when trying to move the object in a different direction. After many different attempts, for the life of me, I cannot get the object to stop when it touches edges with obstacles. How can I get this to happen?

1

There are 1 best solutions below

1
On

If two rects share an edge, they don't intersect, they touch. For example, this code:

CGRect rect1 = CGRectMake(0, 0, 100, 100);
CGRect rect2 = CGRectMake(0, 100, 100, 100);

if (CGRectIntersectsRect(rect1, rect2)) {
    NSLog(@"The intersection rect is %@", NSStringFromCGRect(CGRectIntersection(rect1, rect2)));
} else {
    NSLog(@"The rects don't intersect.");
}

will output "The rects don't intersect."

There's no built-in CGRect function to determine if two rects are touching, but you could write one that iterates through the 4 possibilities.