0

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:

enter image description here

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?

4

2 回答 2

1

查看调试绘制代码,我发现了这一点:

#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

看起来你可以从精灵的quad属性中得到你想要的东西。或者可能是第二种解决方案,因为我不知道 cocos2d 在这里所说的边界框和纹理框是什么意思。

于 2013-11-09T21:43:30.223 回答
1

这是我想出的代码,作为我的自定义子类中的一个函数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]);
}
于 2013-11-09T22:26:15.880 回答