本文是根据王迪老师的视频教程做出的学习笔记,想要看视频教程的童鞋看这里,传送门,另外想看更加系统的文字教程的童鞋也可以看这里,传送门。
实现的效果如下:
原理:
有三个对象:模板,底板(ClippingNode),背景,其实就是根据一个模板(Stencil)形状切割底板,图示:
代码实现如下:因为所用的图片都是cocos2dx自带的cpp的图片,这里就不列举了。
Size visibleSize = Director::getInstance()->getVisibleSize();
auto bg=Sprite::create("HelloWorld.png");
bg->setPosition(visibleSize/2);
this->addChild(bg);
auto sprite=Sprite::create("target.jpg");
sprite->setScale(0.6f);
sprite->setPosition(visibleSize/2);
nodef=Node::create();
clip=ClippingNode::create();
clip->setStencil(nodef);
clip->setInverted(true); //设置底板可见
clip->setAlphaThreshold(0.0f); //设置alpha透明度
this->addChild(clip);
clip->addChild(sprite);
auto dispatcher=Director::getInstance()->getEventDispatcher();
auto listener=EventListenerTouchOneByOne::create();
listener->onTouchBegan=CC_CALLBACK_2(ClippingNodeTest::onTouchBegan,this);
listener->onTouchEnded=CC_CALLBACK_2(ClippingNodeTest::onTouchEnded,this);
listener->setSwallowTouches(false); //不向下传递
dispatcher->addEventListenerWithSceneGraphPriority(listener,this);
然后是触摸监听的代码:
bool ClippingNodeTest::onTouchBegan(cocos2d::Touch * touch,cocos2d::Event * event){
auto pos=this->convertToNodeSpace(touch->getLocation());
auto holdBg=Sprite::create("hole_effect.png");
holdBg->setPosition(pos);
clip->addChild(holdBg);
auto effect=Sprite::create("hole_stencil.png");
effect->setPosition(pos);
nodef->addChild(effect);
return false;
}