cocos2d-x 3.x 不规则点击区域

这篇博客介绍了如何在cocos2d-x 3.x版本中实现不规则点击区域,通过使用RenderTexture和CCImage获取精灵上的像素信息,判断点击是否在目标区域内,提供了一种在3.x版本中模拟2.x绘制行为的方法。

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

网上打部分不规则点击教程都是针对cocos2d-2.x的,因为那时draw()函数里会立即绘制。3.x不一样了,一边如此我们也可以让他以2.x的工作方式来绘制。直接贴代码了



void HelloWorld::testPixel() 
{
auto s = Director::getInstance()->getWinSize();  
auto sp = Sprite::create("HelloWorld.png");  
sp->setPosition(s / 2);  
addChild(sp);  

Size size = sp->getContentSize();  
auto m_rt = RenderTexture::create(size.width, size.height, Texture2D::PixelFormat::RGBA8888);  


// 绘画开始  
m_rt->begin();  
// 绘制  
sp->visit();  
// 结束绘制  
m_rt->end();  
Director::getInstance()->getRenderer()->render();  //加这句 
// 通过画布拿到这张画布上每个像素点的信息,封装到CCImage中  
pImage = m_rt->newImage();  


auto listen = EventListenerTouchOneByOne::create();  
listen->setSwallowTouches(false);  
listen->onTouchBegan = [&](Touch* touch, Event* event){  
auto target = static_cast<Sprite*>(event->getCurrentTarget());  
if(target->getBoundingBox().containsPoint(touch->getLocation()))  
{  
//获取像素数据  
Color4B color4B;  
Vec2 nodePos = target->convertTouchToNodeSpace(touch);  
unsigned int x = nodePos.x;  
unsigned int y = target->getContentSize().height - nodePos.y;  


unsigned char* data_ = pImage->getData();  
unsigned int *pixel = (unsigned int *)data_;  
pixel = pixel + (y * (int)target->getContentSize().width) * 1 + x * 1;  
//R通道  
color4B.r = *pixel & 0xff;  
//G通道  
color4B.g = (*pixel >> 8) & 0xff;  
//B通过  
color4B.b = (*pixel >> 16) & 0xff;  
//Alpha通道,我们有用的就是Alpha  
color4B.a = (*pixel >> 24) & 0xff;  


if(color4B.a == 0)  
{  
log("tou ming..............");  
}  
else
{
log("bu tou ming..............");  
}
}  
return true;  
};  
_eventDispatcher->addEventListenerWithSceneGraphPriority(listen, sp);  








}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值