views:

359

answers:

1

I have written a class extending UIImageView in order to allow me dynamically generate bricks on screen. The brick is a 20x10 PNG.

Here is my codes:

- (id) initBrick:(NSInteger *)str x:(float)ptX y:(float)ptY {
int brickIndex = arc4random() % 10 + 1;
NSString *filename = [NSString stringWithFormat:@"brick%d.png", brickIndex];

UIImage *brickImage = [UIImage imageNamed:filename];
CGRect imageRect = CGRectMake(0.0f, 0.0f, 20.0f, 10.0f);
[self initWithFrame:imageRect];
[self setImage:brickImage];
self.center = CGPointMake(ptX, ptY);
self.opaque = YES;
self.isDead = NO;
return self;
}

Then, I have a simple collision detection function in the same class:

- (BOOL)checkHit:(CGRect)frame {
if(CGRectIntersectsRect(self.frame, frame)) {
 isDead = YES;
 return YES;
} else {
 return NO;
}

}

But the collision detection is not performed well. The bounding box seems a bit lower than my image. How to show the bounding box in order to allow me to check the collision?

If the code is unclear, I can supply more information.

+2  A: 

You could set the background color to be sure the problem is not caused by the image. But if the image is simple opaque rectangle, it should be fine. I’d set a breakpoint in the checkHit method, see what self.frame gives and think for a while, it can’t be too hard.

And as for the checkHit method, you should either rename it to checkAndSetHit, or (better) do not set the dead flag there:

- (BOOL) checkHit: (CGRect) frame
{
    return CGRectIntersectsRect(self.frame, frame);
}

The code would read even a tiny little bit better if you renamed it to hitsFrame or intersectsFrame, but that’s nitpicking.

zoul
Agree with this. If you really want to also draw the frame of your view, just override drawRect: in your class, and do so there. (Don't forget to call super!)
Sixten Otto
Thanks for comments from you guys. I have moved the isDead codes back to my main game class codes. (p.s. I just started iPhone programming 2 days ago, a really newbie)
Shivan Raptor