cocos2dx 3.x 蒙板 遮罩 点击圆功能

//注册触摸
    EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this);
    listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved,this);
    listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded,this);
    listener->setSwallowTouches(true);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    //创建一个遮罩
    LayerColor *m_pLyaerColor = LayerColor::create(ccc4(0, 0, 0, 110));

    //创建剪裁节点
    ClippingNode *pClip = ClippingNode::create();
    pClip->setInverted(true);//是否反向,true 圆是透明,其他是黑, false 圆是黑,其他透明
    addChild(pClip);

    //将遮罩添加到裁剪节点上
    pClip->addChild(m_pLyaerColor);

    //绘制圆区域
    //设置参数
    ccColor4F red = ccc4f(1, 0, 0, 1);
    float radius = 55.0f;//圆的半径
    const int pCount = 200;//顶点数,将圆看成是200边型
    float angel = 2.0f * (float)M_PI / pCount;//两个顶点与中心的夹角(弧度)
    Point m_vPoint[pCount]; 
    for (int i = 0; i < pCount; i++)
    {
        float radian = i * angel;//弧度
        m_vPoint[i].x = radius * cosf(radian);//顶点X坐标
        m_vPoint[i].y = radius * sinf(radian);//顶点Y坐标
    }
    
    //绘制多边形
    //注意不要将pStencil addChild
    DrawNode *pStencil = DrawNode::create();
    pStencil->drawPolygon(m_vPoint, pCount, red, 0, red);//绘制这个多边型
    pStencil->setPosition(Vec2(visibleSize.width /2 , visibleSize.height /2));
    //将这个圆形从裁剪节点上面抠出来, Stencil是模版的意思
    pClip->setStencil(pStencil);
 

 


bool HelloWorld::onTouchBegan(Touch *touch, Event *event){
    
    Size size = Director::getInstance()->getWinSize();
    Vec2 location = touch->getLocation();//获取点击的坐标
    
    float b = abs(location.x - size.width / 2);//获取绝对值
    float c = abs(location.y - size.height / 2);//坐标x.y - 圆心x,y  size/2是圆心.

    if (b <= 55.0f && c <= 55.0f)
    {
        log("dianjidaole");//小于55  点击到了圆
        return true; 
    }

    log("meiyou");
    return false;
}


local stencil= cc.Sprite:create('res/mark.png')

local c_node = cc.ClippingNode:create()
c_node:setStencil(stencil)
c_node:setInverted(false)
c_node:setAlphaThreshold(0)

local sp = cc.Sprite:create('res/di.png')
c_node:addChild(sp)
layer:addChild(c_node)
c_node:setPosition(origin.x+visibleSize.width/2,origin.y+visibleSize.height/2)

猜你喜欢

转载自blog.csdn.net/twicetwice/article/details/80562679
今日推荐