【问题标题】:Detect transparent part on the sprite in cocos2d?在cocos2d中检测精灵上的透明部分?
【发布时间】:2012-09-08 19:33:44
【问题描述】:

我是 Cocos2d 的初学者。我有一个精灵,我想忽略对该精灵透明区域的触摸。

我知道这个答案Cocos2d 2.0 - Ignoring touches to transparent areas of layers/sprites,还有这篇很棒的文章http://www.learn-cocos2d.com/2011/12/fast-pixelperfect-collision-detection-cocos2d-code-1of2/

我能够使其与 KKPixelMaskSprite 一起使用,但仅当从文件中使用 sprite 而不是从批处理节点使用时。每当我使用批处理节点(Sprite 表)来获取 sprite 时,它​​就会停止工作。

我有不同的精灵,我想用这种方式检测 -> 如果触摸在当前的精灵边界框中,那部分在精灵上是否透明?

P.S.我正在使用 cocos2d 1.0。我现在不想使用任何物理引擎,我只想忽略对精灵透明区域的触摸(使用批处理节点创建)。我该怎么做?或者是否有任何工具可以提供帮助?

非常感谢。

【问题讨论】:

标签: objective-c cocos2d-iphone


【解决方案1】:

您可以使用 CGMutablePathRef 进行非矩形精灵碰撞检测。

//检查

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

////创建路径

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);

【讨论】:

    【解决方案2】:

    这个答案比你想象的更分散,因为我不会给你一个代码示例,但这是我实现它的方式:

    您有精灵边界框的位置(精灵的角落,包括透明区域,如果适用),以及屏幕上的触摸位置。使用此信息,您可以计算出触摸 inside 精灵的位置。换句话说,你可以找到触摸的像素,独立于游戏屏幕。

    现在您有了像素位置(x 和 y),打开图像(可能是 PNG),并获取该像素的 RGB[A] 值。每个 PNG 都有一个透明度键。这是 alpha 通道 如果 (x;y) == 透明度键处的 PNG 内部像素颜色,则该像素是透明的

    如果您可以获得相关像素的 alpha 值,如果它等于 0,则该像素是透明的。

    编辑:语义(“alpha 通道”)

    【讨论】:

    • 我已经尝试过该解决方案,它已在我的问题中链接,但无法使其适用于 Batch Node 。谢谢。
    【解决方案3】:

    我会尝试为我更改您的 is Touch 中的边界框,并为不同的精灵减少它...

    【讨论】:

    • 谢谢,我现在使用的,我已经为每个精灵调整了BoundingBox。不好的是,它只能是矩形。无论如何感谢您的回答,+1 upvote。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多