Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

objective c - Detect transparent part on the sprite in cocos2d?

I'm beginner in Cocos2d. I have a sprite, and I want to ignore touch on transparent area of that sprite.

I'm aware of this answer Cocos2d 2.0 - Ignoring touches to transparent areas of layers/sprites, and also this great article http://www.learn-cocos2d.com/2011/12/fast-pixelperfect-collision-detection-cocos2d-code-1of2/.

I was able to make it work with KKPixelMaskSprite, but only when sprite is used from file, but not from batch node. Whenever I use batch node (Sprite sheet), to get sprite , it stops working.

I have different sprites on each other, and I want detect this way -> if touch is in current sprite bounding box, is that part transparent on sprite or no?

P.S.I'm using cocos2d 1.0. I don't want to use any Physics engine for now, I just want to ignore touches on transparent areas of sprite (that was created using batch node ) .How can I do that? Or might there any tool can be helpfull?

Thanks a lot in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use CGMutablePathRef to make non-rectangular sprite collision detection.

//checking

    CGPoint loc =[mySprite convertToNodeSpace:touchPoint];

    if([mySprite isPointInsideMap:loc]) 
    {
         //touched inside..
    }

//Add this method in your MySprite class derived from CCSprite.
-(bool)isPointInsideMap:(CGPoint)inPoint
{
    if (CGPathContainsPoint(mCollisionPath, NULL, inPoint, NO) ) 
    {
        return true;
    }

    return false;
}

////Create Path

CGMutablePathRef  mCollisionPath = CGPathCreateMutable();
CGPathMoveToPoint(mCollisionPath,    NULL,  0, 0 );
CGPathAddLineToPoint(mCollisionPath, NULL,   11, 82 );
CGPathAddLineToPoint(mCollisionPath, NULL,   42, 152 );
CGPathAddLineToPoint(mCollisionPath, NULL,   86, 202 );
CGPathAddLineToPoint(mCollisionPath, NULL,   169, 13 );
CGPathCloseSubpath(mCollisionPath);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...