您的位置:首页 > 移动开发 > Cocos引擎

《Cocos2d-x for iPhone游戏开发实例详解---1.2 绘制精灵》

2013-08-17 00:41 513 查看
《Cocos2d-x for iPhone游戏开发实例详解》系列博文,基于 人民邮电出版社 《Cocos2d for iPhone游戏开发实例详解》一书,使用Cocosd-x技术重写。示例代码中所引用的相关资料归于原书作者 Nathan
Burba 以及出版社所有,本系列博文提供的C++版代码仅供学习使用。

======================================================================================

开发环境:

  Cocos2d-x  cocos2d-2.1rc0-x-2.1.2-hotfix.zip
@ Apr.08, 2013

  MacBook Pro 13'  Mountain Lion 10.8.3

  Xcode 4.6

  iPhone5   IOS 6.1.4

======================================================================================

本示例展示了绘制精灵的基本方法。



//****************************************************************************************************
//            Author:          Last Ranker
//            DateTime:        2013年08月15日
//            SearchMe:        http://blog.csdn.net/lastranker //            Email:           tubufeng@foxmail.com
//
//****************************************************************************************************

//  DrawingSprites.h
//  Chapter_1
//
//  Created by Last Ranker on 13-8-15.
//
//

#ifndef __Chapter_1__DrawingSprites__
#define __Chapter_1__DrawingSprites__

#include <iostream>
#include "cocos2d.h"
using namespace cocos2d;

enum {
TAG_ALICE_SPRITE = 0,
TAG_CAT_SPRITE = 1,
TAG_TREE_SPRITE_1 = 2,
TAG_TREE_SPRITE_2 = 3,
TAG_TREE_SPRITE_3 = 4,
TAG_CLOUD_BATCH = 5,
TAG_GRASS_BATCH_1 = 6,
TAG_GRASS_BATCH_2 = 7
};
class DrawingSprite:public cocos2d::CCLayer
{
public:
virtual bool init();
static cocos2d::CCScene * scene();
CREATE_FUNC(DrawingSprite);
CCLayer * runRecipe();
void drawColorSpriteAt(CCPoint postion,CCRect rect,ccColor3B color,float z);
};
#endif /* defined(__Chapter_1__DrawingSprites__) */

//****************************************************************************************************
//            Author:          Last Ranker
//            DateTime:        2013年08月15日
//            SearchMe:        http://blog.csdn.net/lastranker //            Email:           tubufeng@foxmail.com
//
//****************************************************************************************************

//  DrawingSprites.cpp
//  Chapter_1
//
//  Created by Last Ranker on 13-8-15.
//
//

#include "DrawingSprites.h"
using namespace cocos2d;

CCScene * DrawingSprite::scene()
{
CCScene *scene=CCScene::create();
DrawingSprite *layer=DrawingSprite::create();
scene->addChild(layer);
return scene;

}

bool DrawingSprite::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
runRecipe();
return true;
}
CCLayer * DrawingSprite::runRecipe()
{
/*** Draw a sprite using CCSprite ***/
CCSprite *tree1=CCSprite::create("tree.png");
tree1->setPosition(ccp(20, 20));
tree1->setAnchorPoint(ccp(0.5f, 0));
tree1->setScale(1.5f);
this->addChild(tree1,2, TAG_TREE_SPRITE_1);

/*** Load a set of spriteframes from a PLIST file and draw one by name ***/

//Get the sprite frame cache singleton
CCSpriteFrameCache *cache=CCSpriteFrameCache::sharedSpriteFrameCache();

//Load our scene sprites from a spritesheet
cache->addSpriteFramesWithFile("alice_scene_sheet.plist");

//Specify the sprite frame and load it into a CCSprite
CCSprite *alice=CCSprite::createWithSpriteFrameName("alice.png");
//Generate Mip Maps for the sprite
alice->getTexture()->generateMipmap();
ccTexParams texParams={GL_LINEAR_MIPMAP_LINEAR,GL_LINEAR,GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE};
alice->getTexture()->setTexParameters(&texParams);

//Set other information.
alice->setPosition(ccp(120, 20));
alice->setScale(0.4f);
alice->setAnchorPoint(ccp(0.5f, 0));
this->addChild(alice, 2, TAG_ALICE_SPRITE);

//Make Alice grow and shrink.
alice->runAction(CCRepeatForever::create((CCActionInterval*)CCSequence::create(CCScaleTo::create(4.0f, 0.7f),CCScaleTo::create(4.0f, 0.1f),NULL)));

/*** Draw a sprite using CCTexture2D ***/
CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage("tree.png");
CCSprite *tree2=CCSprite::createWithTexture(texture);
tree2->setPosition(ccp(300, 20));
tree2->setAnchorPoint(ccp(0.5f, 0));
tree2->setScale(2.0f);
this->addChild(tree2, 2, TAG_TREE_SPRITE_2);

/*** Draw a sprite using CCSpriteFrameCache and CCTexture2D ***/
CCSpriteFrame *frame=CCSpriteFrame::createWithTexture(texture, tree2->getTextureRect());
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFrame(frame, "tree.png");
CCSprite *tree3=CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("tree.png"));
tree3->setPosition(ccp(400, 20));
tree3->setAnchorPoint(ccp(0.5f, 0));
tree3->setScale(1.25f);
this->addChild(tree3,2, TAG_TREE_SPRITE_3);

/*** Draw sprites using CCBatchSpriteNode ***/

//Clouds
CCSpriteBatchNode *cloudBatch=CCSpriteBatchNode::create("cloud_01.png", 10);
this->addChild(cloudBatch, 1, TAG_CLOUD_BATCH);
for (int x=0; x<10; x++) {
// CCSprite *s=CCSprite::create(cloudBatch->getTexture(),CCRectMake(0, 0, 64, 64));
CCSprite *s=CCSprite::createWithTexture(cloudBatch->getTexture(), CCRectMake(0, 0, 64, 64));
s->setOpacity(100);
cloudBatch->addChild(s);
s->setPosition(ccp(arc4random()%500-50,arc4random()%150+200));
}

//Middleground Grass
int capacity=10;
CCSpriteBatchNode *grassBatch1=CCSpriteBatchNode::create("grass_01.png", capacity);
this->addChild(grassBatch1, 1,TAG_GRASS_BATCH_2);
for (int x=0; x<capacity; x++) {
CCSprite *s=CCSprite::createWithTexture(grassBatch1->getTexture(), CCRectMake(0, 0, 64, 64));
s->setOpacity(255);
grassBatch1->addChild(s);
s->setPosition(ccp(arc4random()%500-50,arc4random()%20+70));
}

//Foreground Grass
CCSpriteBatchNode *grassBatch2=CCSpriteBatchNode::create("grass_02.png",10);
this->addChild(grassBatch2, 1,TAG_GRASS_BATCH_2);
for (int x=0; x<30; x++) {
CCSprite *s=CCSprite::createWithTexture(grassBatch2->getTexture(), CCRectMake(0, 0, 64, 64));
s->setOpacity(255);
grassBatch2->addChild(s);
s->setPosition(ccp(arc4random()%500-50,arc4random()%40-10));
}

/*** Draw colored rectangles using a 1px x 1px white texture ***/

//Draw the sky using blank.png
this->drawColorSpriteAt(ccp(240,190), CCRectMake(0, 0, 480, 260), ccc3(150, 200, 200), 0);

//Draw the ground using blank.png
this->drawColorSpriteAt(ccp(240,30), CCRectMake(0, 0, 480, 60), ccc3(80,50,25),0);
return  this;
}
void DrawingSprite::drawColorSpriteAt(CCPoint postion,CCRect rect,ccColor3B color,float z)
{
CCSprite *sprite=CCSprite::create("blank.png", rect);
sprite->setPosition(postion);
sprite->setColor(color);
this->addChild(sprite,z);
}


This recipe takes us through most of the common ways of drawing sprites:f
Creating a CCSprite from a file:

First, we have the simplest way to draw a sprite. This involves using the
CCSpriteclass method as follows:

+(id)spriteWithFile:(NSString*)filename;

This is the most straightforward way to initialize a sprite and is adequate for manysituations.

f Other ways to load a sprite from a file:

After this, we will see examples of
CCSprite
creation using
UIImage/CGImageRef,CCTexture2D,
and a CCSpriteFrame
instantiated using a
CCTexture2D
object.CGImageRef
support allows you to tie Cocos2d into other frameworks and toolsets.CCTexture2D
is the underlying mechanism for texture creation.

f Loading spritesheets using CCSpriteFrameCache:

Next, we will see the most powerful way to use sprites, the
CCSpriteFrameCacheclass. Introduced in
Cocos2d-iPhone v0.99, the
CCSpriteFrameCachesingleton is a cache of all sprite frames. Using a
spritesheet
and its associatedPLIST
file (created using
Zwoptex, more on this later) we can load multiple spritesinto the cache. From here we can create
CCSprite
objects with sprites from thecache:

+(id)spriteWithSpriteFrameName:(NSString*)filename;

f Mipmapping:

Mipmapping allows you to scale a texture or to zoom in or out of a scene withoutaliasing your sprites. When we scale Alice down to a small size, aliasing will inevitablyoccur. With mipmapping
turned on, Cocos2d dynamically generates lower resolutiontextures to smooth out any pixelation at smaller scales. Go ahead and comment outthe following lines:

[alice.texture generateMipmap];
ccTexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR,

GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE };
[alice.texture setTexParameters:&texParams];

Now you should see this pixelation as Alice gets smaller.f
Drawing many derivative sprites with CCSpriteBatchNode:

The CCSpriteBatchNode
class, added in
v0.99.5, introduces an efficient way todraw
and re-draw the same sprite over and over again. A batch node is created withthe following method:

CCSpriteBatchNode *cloudBatch = [CCSpriteBatchNode
batchNodeWithFile:@"cloud_01.png" capacity:10];

Then, you create as many sprites as you want using the follow code:

CCSprite *s = [CCSprite spriteWithBatchNode:cloudBatch
rect:CGRectMake(0,0,64,64)];

[cloudBatch addChild:s];


Setting the capacity to the number of sprites you plan to draw tells Cocos2d toallocate that much space. This is yet
another tweak for extra efficiency, though itis not absolutely necessary that you do this. In these three examples we draw 10randomly
placed clouds and 60 randomly placed bits of grass.

f Drawing colored rectangles:

Finally, we have a fairly simple technique that has a variety of uses. By drawinga sprite with a blank 1px by 1px white texture and then coloring it and setting itstextureRect
property we can create very useful colored bars:

CCSprite *sprite = [CCSprite spriteWithFile:@"blank.png"];
[sprite setTextureRect:CGRectMake(0,0,480,320)];
[sprite setColor:ccc3(255,128,0)];

In this example we have used this technique to create very simple ground andsky backgrounds. 

源代码:http://pan.baidu.com/share/link?shareid=3527479237&uk=1962963338
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Cocos2d-x
相关文章推荐