Cocos2d-x3.1SpriteBatchNode使用

bool NewSpriteBatch::init()
{
    auto bRet = false;
    
    do{
        CC_BREAK_IF(!Layer::init());
        auto touchListener = EventListenerTouchAllAtOnce::create();//多点触摸
        touchListener->onTouchesEnded = CC_CALLBACK_2(NewSpriteBatch::onTouchesEnded, this);//设置触摸结束后的回调函数
        _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);//设置事件监听
        auto BatchNode = SpriteBatchNode::create("grossini_dance_atlas.png");//创建SpriteBatchNode对象
        addChild(BatchNode,0,kTagSpriteBatchNode);//添加SpriteBatchNode对象
        
        bRet = true;
    }while(0);
    return bRet;
}

void NewSpriteBatch::onTouchesEnded(const std::vector<Touch *> &touches, cocos2d::Event *event)
{
    for(auto &touch : touches)
    {
        auto location = touch->getLocation();//获取触摸位置
        addNewSpriteWithCoords(location);//在触摸位置处添加精灵
    }
}
void NewSpriteBatch::addNewSpriteWithCoords(cocos2d::Vec2 p)
{
    auto BatchNode = static_cast<SpriteBatchNode*>(getChildByTag(kTagSpriteBatchNode));//获取SpriteBatchNode对象
    
    int idx = (int)(CCRANDOM_0_1() * 1400 / 100);//CCRANDOM_0_1是0到1之间的随机数
    log("CCRANDOM_0_1 = %lf",CCRANDOM_0_1());
    int x = (idx%5) * 85;//设置x轴坐标
    int y = (idx/5) * 121;//设置y轴坐标
    log("idx5 = %d",idx%5);
    log("idx/5 = %d",idx/5);
    auto sprite = Sprite::createWithTexture(BatchNode->getTexture(),Rect(x, y, 85, 121));//获取本次随机数对象
    BatchNode->addChild(sprite);
    
    sprite->setPosition(Vec2(p.x, p.y));//设置精灵放在触摸位置
    
    ActionInterval* action;
    float random = CCRANDOM_0_1();//根据随机数的大小创建不同的动作
    if(random < 0.20)
        action = ScaleBy::create(3, 2);
    else if(random < 0.40)
        action = RotateBy::create(3, 360);
    else if(random < 0.60)
        action = Blink::create(1, 3);
    else if(random < 0.80)
        action = TintBy::create(2, 0, -255, -255);
    else
        action = FadeOut::create(2);
    
    auto action_back = action->reverse();
    auto seq = Sequence::create(action,action_back, NULL);//动作序列
    sprite->runAction(RepeatForever::create(seq));//执行动作
}


class NewSpriteBatch : public Layer
{
public:
    CREATE_FUNC(NewSpriteBatch);
    virtual bool init();
    
    void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);//触摸事件
    void addNewSpriteWithCoords(Vec2 p);//增加新精灵
};

以上代码是SpriteBatchNode的使用实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值