I need some help with cocos2d DrawNodes blending. I have DrawNode with sprite on it:
And another DrawNode with drawn polygon (polygon area is less than heart sprite). As a result of blending I need to have only a part of heart sprite inside polygon, like this:
My code:
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();
}
}
As a result of this code I see full hart sprite without polygon. I also try to change BlendFunc values, but it not help. Please tell me what I do wrang)
P.S. Thanks! P.S.P.S. Sorry for my english)
It seems that you want to clip the heart sprite using the polygon as a stencil. In that case. You don't have to blend two
DrawNode
. Instead, You can useClippingNode
like:For more
ClippingNode
examples, you can refer to the official sample code: https://github.com/cocos2d/cocos2d-x/tree/v3/tests/cpp-tests/Classes/ClippingNodeTest