Reputation: 14954
I have CCSprite
which (for reasons I'll gloss over here) has some padding around its edges. I'm creating the sprite from a sprite sheet, and it is continuously animating. Here, I've added a semi-transparent blue sprite to show the contentSize
of the sprite. I've also turned on CC_SPRITE_DEBUG_DRAW
in order to draw borders around (both) sprites:
Thus, the blue box represents the boundingBox
/ contentSize
properties of CCSprite
. texture. This is correct, desired functionality.
However... as you can see, CC_SPRITE_DEBUG_DRAW
is able to recognize the actual edges of the drawn texture. I'd like to access the actual "drawn area" (eg, as a CGRect
). In other words: I want to be able to detect if the user touched on the unit as opposed to simply in the blue box (boundingBox
).
How can I access this CGRect
?
Upvotes: 0
Views: 339
Reputation: 14954
Here's the code I came up with, as a function in my custom subclass of CCSprite
:
// In local space
- (CGRect)hitArea {
CGPoint bl = CGPointMake(MIN(_quad.tl.vertices.x, _quad.bl.vertices.x), MIN(_quad.bl.vertices.y, _quad.br.vertices.y));
CGPoint tr = CGPointMake(MAX(_quad.tr.vertices.x, _quad.br.vertices.x), MAX(_quad.tl.vertices.y, _quad.tr.vertices.y));
return CGRectMake(bl.x, bl.y, tr.x - bl.x, tr.y - bl.y);
}
// In game space, like how .boundingBox works
- (CGRect)hitBox {
return CGRectApplyAffineTransform(self.hitArea, [self nodeToParentTransform]);
}
Upvotes: 1
Reputation: 64477
Looking at the debug draw code I found this:
#if CC_SPRITE_DEBUG_DRAW == 1
// draw bounding box
CGPoint vertices[4]={
ccp(_quad.tl.vertices.x,_quad.tl.vertices.y),
ccp(_quad.bl.vertices.x,_quad.bl.vertices.y),
ccp(_quad.br.vertices.x,_quad.br.vertices.y),
ccp(_quad.tr.vertices.x,_quad.tr.vertices.y),
};
ccDrawPoly(vertices, 4, YES);
#elif CC_SPRITE_DEBUG_DRAW == 2
// draw texture box
CGSize s = self.textureRect.size;
CGPoint offsetPix = self.offsetPosition;
CGPoint vertices[4] = {
ccp(offsetPix.x,offsetPix.y), ccp(offsetPix.x+s.width,offsetPix.y),
ccp(offsetPix.x+s.width,offsetPix.y+s.height),
ccp(offsetPix.x,offsetPix.y+s.height)
};
ccDrawPoly(vertices, 4, YES);
#endif // CC_SPRITE_DEBUG_DRAW
It looks like you may be able to get what you want from the sprite's quad
property. Or perhaps its the second solution, because I don't know what cocos2d means by bounding box and texture box here.
Upvotes: 1