Book Image

Cocos2d-x Cookbook

By : Akihiro Matsuura
Book Image

Cocos2d-x Cookbook

By: Akihiro Matsuura

Overview of this book

Table of Contents (18 chapters)
Cocos2d-x Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using a batch node


Renderer speed will be slow if there are a lot of sprites on the screen. However, a shooting game needs a lot of images such as bullets, and so on. In this time, if renderer speed is slow, the game earns a bad review. In this chapter, you will learn how to control a lot of sprites.

How to do it...

Let's try to display a lot of sprites using SpriteBatchNode.

auto batchNode = SpriteBatchNode::create("res/run_01.png");
this->addChild(batchNode);
for (int i=0; i<300; i++) {
    auto sprite = Sprite::createWithTexture(batchNode->getTexture());
    float x = CCRANDOM_0_1() * size.width;
    float y = CCRANDOM_0_1() * size.height;
    sprite->setPosition(Vec2(x,y));
    batchNode->addChild(sprite);
}

How it works...

The SpriteBatchNode instance can be used to do the following:

  • Generate a SpriteBatchNode instance using a texture

  • Add the instance on the layer

  • Generate sprites using the texture in the SpriteBatchNode instance

  • Add these sprites on the SpriteBatchNode instance...