Hello, this is my take on Exercise 6 intersect method, I'd tired this on different scenarios, but perhaps it still need improvement to cover area. Please feel free to try it, and let me know what is the problem, thanks.
-(Rectangle *) intersect: (Rectangle *) rect
{
Rectangle *overlap = [[Rectangle alloc] init];
XYPoint *overlapPoint = [[XYPoint alloc] init];
BOOL xIntersect = NO, yIntersect = NO;
overlap.origin = overlapPoint;
if (self.origin.x + self.width > rect.origin.x || rect.origin.x + rect.width > self.origin.x) {
if (self.origin.x + self.width > rect.origin.x && rect.origin.x + rect.width > self.origin.x && self.origin.x <= rect.origin.x) {
if (self.origin.x <= rect.origin.x){
overlap.origin.x = rect.origin.x;
}
if (self.origin.x + self.width <= rect.origin.x + rect.width){
overlap.width = (self.origin.x + self.width) - overlap.origin.x;
} else if (self.origin.x + self.width > rect.origin.x + rect.width){
overlap.width = (rect.origin.x + rect.width) - overlap.origin.x;
}
xIntersect = YES;
} else if (rect.origin.x + rect.width > self.origin.x && self.origin.x + self.width > rect.origin.x && rect.origin.x <= self.origin.x) {
if (rect.origin.x <= self.origin.x){
overlap.origin.x = self.origin.x;
}
if (rect.origin.x + rect.width <= self.origin.x + self.width){
overlap.width = (rect.origin.x + rect.width) - overlap.origin.x;
} else if (rect.origin.x + rect.width > self.origin.x + self.width){
overlap.width = (self.origin.x + self.width) - overlap.origin.x;
}
xIntersect = YES;
}
} else {
xIntersect = NO;
}
if (self.origin.y + self.height > rect.origin.y || rect.origin.y + rect.height > self.origin.y) {
if (self.origin.y + self.height > rect.origin.y && rect.origin.y + rect.height > self.origin.y && self.origin.y <= rect.origin.y) {
if (self.origin.y <= rect.origin.y){
overlap.origin.y = rect.origin.y;
}
if (rect.origin.y + rect.height <= self.origin.y + self.height){
overlap.height = (rect.origin.y + rect.height) - overlap.origin.y;
} else if (rect.origin.y + rect.height > self.origin.y + self.height){
overlap.height = (self.origin.y + self.height) - overlap.origin.y;
}
yIntersect = YES;
} else if (rect.origin.y + rect.height > self.origin.y && self.origin.y + self.height > rect.origin.y && rect.origin.y <= self.origin.y) {
if (rect.origin.y <= self.origin.y){
overlap.origin.y = self.origin.y;
}
if (self.origin.y + self.height <= rect.origin.y + rect.height){
overlap.height = (self.origin.y + self.height) - overlap.origin.y;
} else if (self.origin.y + self.height > rect.origin.y + rect.height){
overlap.height = (rect.origin.y + rect.height) - overlap.origin.y;
}
yIntersect = YES;
}
} else {
yIntersect = NO;
}
if (!xIntersect || !yIntersect) {
overlap.width = 0;
overlap.height = 0;
overlap.origin.x = 0;
overlap.origin.y = 0;
}
[overlapPoint release];
return overlap;
}