原创作品,转载请标明:http://blog.csdn.net/jackystudio/article/details/11794565
飞机发射子弹要注意的几点是:
1.子弹的渲染效率
2.子弹的初始位置和飞行效果
3.子弹的回收
4.子弹层提供的接口
本文先讲解子弹的渲染效率问题。看两个很典型的例子,将1000个icon图精灵加入游戏。
1.普通渲染
(1)示例
- for(int i = 0;i < 1000;++i){
- int x = arc4random()%960;
- int y = arc4random()%640;
- CCSprite* testIcon = CCSprite::create("Icon.png");
- testIcon->setPosition( ccp(x, y) );
- this->addChild(testIcon);
- }
(2)效果

2.批次渲染
(1)示例
- CCSpriteBatchNode* batchNode = CCSpriteBatchNode::create("Icon.png", 1000);
- batchNode->setPosition(CCPointZero);
- this->addChild(batchNode);
-
- for(int i = 0;i < 1000;++i){
- int x = arc4random()%960;
- int y = arc4random()%640;
- CCSprite* testIcon = CCSprite::createWithTexture(batchNode->getTexture());
- testIcon->setPosition( ccp(x, y) );
- batchNode->addChild(testIcon);
- }
(2)效果图

3.渲染机制
从左下角的渲染次数(第一行)和渲染FPS(第三行),我们就可以看出,普通渲染需要进行1000次,而批次渲染只要1次就可以完成。差别在哪?CCSpriteBatchNode这个精灵批次渲染类。
普通渲染机制:
- 准备,渲染,清除。准备,渲染,清除。...准备,渲染,清除。100次啊100次!!!
批次渲染机制:
- 准备,渲染,渲染....渲染,清除。是不是快多了?
但必须注意的是,使用CCSpriteBatchNode,所有的精灵必须是同一张图,也不能指定精灵的深度,所有精灵必须在同一渲染层。
4.子弹的添加
子弹的添加其实就是使用CCSpriteBatchNode的最佳例子。
- bool BulletLayer::init()
- {
- bool bRet=false;
- do
- {
- CC_BREAK_IF(!CCLayer::init());
- CCTexture2D *texture = CCTextureCache::sharedTextureCache()->textureForKey("ui/shoot.png");
- bulletBatchNode = CCSpriteBatchNode::create(texture);//bulletBatchNode为CCSpriteBatchNode类型成员变量
- this->addChild(bulletBatchNode);
-
- bRet=true;
- } while (0);
- return bRet;
- }
-
- void BulletLayer::AddBullet(float dt)
- {
- CCSprite* bullet=CCSprite::createWithSpriteFrameName("bullet1.png");
- bulletBatchNode->addChild(bullet);//这里子弹要添加到bulletBatchNode中,效果如下左图
- //this->addChild(bullet);换成这句渲染批次和FPS,如下右图
- }
我们这里调用
- this->schedule(schedule_selector(BulletLayer::AddBullet),0.01f);
看一下效果,因为间隔时间0.01s,所以子弹看起来是柱状的,好丑。。。看一下,渲染批次和FPS的比较:一个是4(有其他精灵),另一个则是181。子弹的初始位置和移动在下一篇介绍,先放图。

|