如何在cocos2d中混合两个DrawNode

时间:2016-02-10 18:08:58

标签: c++ c++11 cocos2d-x cocos2d-x-3.0 cocos2d-x-2.x

我需要一些关于cocos2d DrawNodes混合的帮助。我的DrawNode上有精灵:

enter image description here 另一个绘制多边形的DrawNode(多边形区域小于心形精灵)。作为混合的结果,我需要在多边形内只有一部分心形精灵,如下所示: enter image description here 我的代码: TextureNode.h

class CTextureNode : public cocos2d::DrawNode
{
public:
static CTextureNode * create(const std::string & fileName, const cocos2d::Rect & rect);

CTextureNode();
virtual ~CTextureNode();

void setPolygonalMask(const cocos2d::Vec2 * verts, int count);

private:
bool initTexture(const std::string & fileName, const cocos2d::Rect & rect);

private:
cocos2d::DrawNode * m_pMask;
cocos2d::Sprite * m_pSprite;

float timeOutline;
bool bShaderInc;
};

TextureNode.cpp

CTextureNode * CTextureNode::create(const std::string & fileName, const cocos2d::Rect & rect)
{
auto ret = new CTextureNode();
if (!ret || !ret->init() || !ret->initTexture(fileName, rect))
{
    CC_SAFE_DELETE(ret);
}

return ret;
}

CTextureNode::CTextureNode()
: timeOutline(0.f)
, bShaderInc(true)
, m_pMask(nullptr)
, m_pSprite(nullptr)
{
}

CTextureNode::~CTextureNode()
{
}

bool CTextureNode::initTexture(const std::string & fileName, const cocos2d::Rect & rect)
{
m_pSprite = cocos2d::Sprite::create(fileName, rect);
m_pSprite->setAnchorPoint(cocos2d::Point::ZERO);
addChild(m_pSprite);

m_pMask = cocos2d::DrawNode::create();
m_pMask->setPosition(cocos2d::Point::ZERO);
m_pMask->setAnchorPoint(cocos2d::Point::ZERO);
addChild(m_pMask);

return true;
}

void CTextureNode::setPolygonalMask(const cocos2d::Vec2 * verts, int count)
{
if (m_pMask)
{
    m_pMask->drawPolygon(verts, count, cocos2d::Color4F::WHITE, 1, cocos2d::Color4F::WHITE);

    cocos2d::BlendFunc maskBlendFunc = { GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA };
    m_pMask->setBlendFunc(maskBlendFunc);

    auto size = m_pSprite->getContentSize();

    auto renderer = cocos2d::RenderTexture::create(size.width, size.height, cocos2d::Texture2D::PixelFormat::RGBA8888);
    renderer->begin();

    m_pMask->visit();

    renderer->end();
}
}

作为这段代码的结果,我看到没有多边形的完整哈特精灵。我也尝试更改BlendFunc值,但它没有帮助。 请告诉我我做的事情)

P.S。谢谢! P.S.P.S.对不起我的英文)

1 个答案:

答案 0 :(得分:0)

似乎您想要使用多边形作为模板来剪切心形精灵。在这种情况下。您不必混合两个DrawNode。相反,您可以使用ClippingNode之类的:

auto heartSprite = cocos2d::Sprite::create(fileName);

auto stencil = DrawNode::create();
stencil->drawPolygon(verts, count, cocos2d::Color4F::WHITE, 1, cocos2d::Color4F::WHITE);

auto clipper = ClippingNode::create();
clipper->setStencil(stencil);
clipper->addChild(heartSprite)

有关更多ClippingNode示例,您可以参考官方示例代码:https://github.com/cocos2d/cocos2d-x/tree/v3/tests/cpp-tests/Classes/ClippingNodeTest