开发者

how to detect touch on rotated sprite in cocos2d

开发者 https://www.devze.com 2023-04-09 23:01 出处:网络
I have rotated sprite to 90. I checked the touch location of the rotated sprite as follows: matchsprite.rotation=90;

I have rotated sprite to 90. I checked the touch location of the rotated sprite as follows:

matchsprite.rotation=90;

CGRect r=CGRect开发者_运维百科Make(matchstick.position.x, matchstick.position.y, matchstick.contentSize.height,matchstick.contentSize.width);
if(CGRectContainsPoint(r, location))    
    NSLog(@"Hii");

What is the error in this code? I didnt get "Hii". How to detect whether we tap that rotated sprite or not?


Here are the two CCNode extension (category) methods I've added to the Kobold2D game engine:

-(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];
}

Testing if a point is on a sprite (or label or any other node) then is as simple as:

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


The position property of ccsprite gives you the centre coordinate and not the top left corner position.

you can get the rect made like this

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

I am not sure if you need to subtract or add half of the width but i think you can do a little R&D on it.

0

精彩评论

暂无评论...
验证码 换一张
取 消