如何在cocos2d中检测旋转精灵上的触摸

时间:2011-10-03 11:25:39

标签: cocos2d-iphone

我已将精灵旋转到90.我检查了旋转精灵的触摸位置,如下所示:

matchsprite.rotation=90;

CGRect r=CGRectMake(matchstick.position.x, matchstick.position.y, matchstick.contentSize.height,matchstick.contentSize.width);
if(CGRectContainsPoint(r, location))    
    NSLog(@"Hii");

此代码中的错误是什么?我没有得到“Hii”。如何检测我们是否点击了旋转的精灵?

2 个答案:

答案 0 :(得分:1)

以下是我添加到Kobold2D游戏引擎的两种CCNode扩展(类别)方法:

-(BOOL) containsPoint:(CGPoint)point
{
    CGRect bbox = CGRectMake(0, 0, contentSize_.width, contentSize_.height);
    CGPoint locationInNodeSpace = [self convertToNodeSpace:point];
    return CGRectContainsPoint(bbox, locationInNodeSpace);
}

-(BOOL) containsTouch:(UITouch*)touch
{
    CCDirector* director = [CCDirector sharedDirector];
    CGPoint locationGL = [director convertToGL:[touch locationInView:director.openGLView]];
    return [self containsPoint:locationGL];
}

测试一个点是否在精灵(或标签或任何其他节点)上,然后就像这样简单:

UITouch* uiTouch = [touches anyObject];
if ([aSprite containsTouch:uiTouch])
{
    // do something
}

答案 1 :(得分:0)

ccsprite的position属性为您提供中心坐标,而不是左上角位置。

你可以像这样制作矩形

CGRect r=CGRectMake(matchstick.position.x - matchstick.contentSize.width / 2, matchstick.position.y + matchstick.contentSize.height / 2, matchstick.contentSize.height, matchstick.contentSize.width);

我不确定你是否需要减去或增加一半宽度,但我认为你可以做一点R& D。