ClippingNode裁切节点

本文介绍如何使用Cocos2d-x通过模板(Stencil)形状裁剪底板(ClippingNode),实现特定图形显示效果,并提供触摸监听代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文是根据王迪老师的视频教程做出的学习笔记,想要看视频教程的童鞋看这里,传送门,另外想看更加系统的文字教程的童鞋也可以看这里,传送门

实现的效果如下:


原理:

有三个对象:模板,底板(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;
}


ok,搞定,下班!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值