天天看点

cocos2d-x与精灵共舞

注:译者水平有限,欢迎大家批评斧正。

cocos2d是一个具有丰富的图形处理api,它可以使游戏开发者可以轻松地使用广泛的功能。本文将讨论一下sprites的基本用法。

绘制sprites

在2d游戏开发中最基本的任务就是绘制一个sprite。在这个领域里,cocosd给用户提供了很多的灵活性。在本小节里,我们将介绍如何使用ccsprite, spritesheets, ccspriteframecache, 和 ccspritebatchnode来绘制sprite。我们也会再次熟悉一下mipmaping。本节中我们会看到《愛麗絲鏡中奇遇》中的一个场景。

cocos2d-x与精灵共舞

准备

继续….

执行如下代码:

<code>@implementation ch1_drawingsprites -(cclayer*) runrecipe { /*** draw a sprite using ccsprite ***/ ccsprite *tree1 = [ccsprite spritewithfile:@"tree.png"];</code>

//position the sprite using the tree base as a guide (y anchor

point = 0)

[tree1 setposition:ccp(20,20)];

tree1.anchorpoint = ccp(0.5f,0);

[tree1 setscale:1.5f];

[self addchild:tree1 z:2 tag: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 spritewithspriteframename:@"alice.png"];

//generate mip maps for the sprite

[alice.texture generatemipmap];

cctexparams texparams = { gl_linear_mipmap_linear, gl_linear, gl_

clamp_to_edge, gl_clamp_to_edge };

[alice.texture settexparameters:&amp;texparams];

//set other information.

[alice setposition:ccp(120,20)];

[alice setscale:0.4f];

alice.anchorpoint = ccp(0.5f,0);

//add alice with a zorder of 2 so she appears in front of other

sprites

[self addchild:alice z:2 tag:tag_alice_sprite];

//make alice grow and shrink.

[alice runaction: [ccrepeatforever actionwithaction:

[ccsequence actions:[ccscaleto actionwithduration:4.0f scale

:0.7f], [ccscaleto actionwithduration:4.0f scale:0.1f], nil] ] ];

/*** draw a sprite cgimageref ***/

uiimage *uiimage = [uiimage imagenamed: @"cheshire_cat.png"];

cgimageref imageref = [uiimage cgimage];

ccsprite *cat = [ccsprite spritewithcgimage:imageref key:@

"cheshire_cat.png"];

[cat setposition:ccp(250,180)];

[cat setscale:0.4f];

[self addchild:cat z:3 tag:tag_cat_sprite];

/*** draw a sprite using cctexture2d ***/

cctexture2d *texture = [[cctexturecache sharedtexturecache]

addimage:@”tree.png”];

ccsprite *tree2 = [ccsprite spritewithtexture:texture];

[tree2 setposition:ccp(300,20)];

tree2.anchorpoint = ccp(0.5f,0);

[tree2 setscale:2.0f];

[self addchild:tree2 z:2 tag:tag_tree_sprite_2];

/*** draw a sprite using ccspriteframecache and cctexture2d ***/

ccspriteframe *frame = [ccspriteframe framewithtexture:texture

rect:tree2.texturerect];

[[ccspriteframecache sharedspriteframecache] addspriteframe:

frame name:@”tree.png”];

ccsprite *tree3 = [ccsprite spritewithspriteframe:[[ccspriteframe

cache sharedspriteframecache] spriteframebyname:@”tree.png”]];

[tree3 setposition:ccp(400,20)];

tree3.anchorpoint = ccp(0.5f,0);

[tree3 setscale:1.25f];

[self addchild:tree3 z:2 tag:tag_tree_sprite_3];

/*** draw sprites using ccbatchspritenode ***/

//clouds

ccspritebatchnode *cloudbatch = [ccspritebatchnode

batchnodewithfile:@"cloud_01.png" capacity:10];

[self addchild:cloudbatch z:1 tag:tag_cloud_batch];

for(int x=0; x ccsprite *s = [ccsprite spritewithbatchnode:cloudbatch

rect:cgrectmake(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

batchnodewithfile:@"grass_01.png" capacity:capacity];

[self addchild:grassbatch1 z:1 tag:tag_grass_batch_1];

for(int x=0; x ccsprite *s = [ccsprite spritewithbatchnode:grassbatch1

[s setopacity:255];

[grassbatch1 addchild:s];

[s setposition:ccp(arc4random()%500-50, arc4random()%20+70)];

//foreground grass

ccspritebatchnode *grassbatch2 = [ccspritebatchnode

batchnodewithfile:@"grass_01.png" capacity:10];

[self addchild:grassbatch2 z:3 tag:tag_grass_batch_2];

for(int x=0; x ccsprite *s = [ccsprite spritewithbatchnode:grassbatch2

[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

[self drawcoloredspriteat:ccp(240,190) withrect:cgrectma

ke(0,0,480,260) withcolor:ccc3(150,200,200) withz:0];

//draw the ground using blank.png

[self drawcoloredspriteat:ccp(240,30)

withrect:cgrectmake(0,0,480,60) withcolor:ccc3(80,50,25) withz:0];

return self;

-(void) drawcoloredspriteat:(cgpoint)position withrect:(cgrect)rect

withcolor:(cccolor3b)color withz:(float)z {

ccsprite *sprite = [ccsprite spritewithfile:@"blank.png"];

[sprite setposition:position];

[sprite settexturerect:rect];

[sprite setcolor:color];

[self addchild:sprite];

//set z order

[self reorderchild:sprite z:z];

@end

它是如何工作的….

本节给我们介绍了绘制sprite的一般方法:

从一个文件中创建一个ccsprite:

首先,介绍一些绘制一个sprite的最简单的方法。这涉及到使用ccsprite类方法,如下:

<code>+(id)spritewithfile:(nsstring*)filename;</code>

这是初始化一个sprite的最直接的方法,并且适合很多种情况。

从一个文件中加载一个sprite的另一种方法:

之后我们将看到使用uiimage/cg/imageref,cctexture2d来创建ccsprite的例子,还有使用一个cctexture2d对象创建ccspriteframe的例子。cgimageref支持将cocos2d绑定到其他的框架和工具。cctexture2d是创建纹理的底层机制。

使用ccspriteframecache加载spritesheet:

下面,我们将看到使用sprite的最美妙的方法,就是ccspriteframecache类。ccspriteframecache对象是所有sprite帧的缓存,在cocosd-iphone v0.99中有介绍。使用一个spritesheet和它相关联的plist文件,我们可以加载多个sprite到缓存中。使用下面的代码我们可以使用缓存中的sprite创建ccsprite:

<code>+(id)spritewithspriteframename:(nsstring*)filename;</code>

mipmaping:

mipmaping允许你缩放一个纹理或者不混淆你的sprites的情况下缩放一个背景。当我们将爱丽丝缩小时,混淆将不能避免地发生。但是开启mipmaping之后,cocos2d将在一个更小区域里动态地产生低分辨率的纹理来事像素化平滑过渡。返回前面的代码,将如下代码注释掉:

<code>[alice.texture generatemipmap]; cctexparams texparams = { gl_linear_mipmap_linear, gl_linear, gl_clamp_to_edge, gl_clamp_to_edge }; [alice.texture settexparameters:&amp;texparams];</code>

现在你可看到爱丽丝的像素画变小了。

使用ccspritebatchnode绘制多个sprite副本。

在v0.99.5版本引入的ccspritebatchnode类介绍了一个重复绘制同一个sprite对象的高效方方达。这是另一个额外高效的方法,虽然你可以不需要不这样做。在这三个例子中我们绘制了10个随机位置的白云和60个随机位置的小草。

绘制彩色的矩形。

最后,有一个经常会用的一个简单技术。通过绘制一个一个空白像素的sprite纹理,然后向其充颜色并设置它的textruerect属性,这样我们就可以创建一个非常有用的色条:

<code>ccsprite *sprite = [ccsprite spritewithfile:@"blank.png"]; [sprite settexturerect:cgrectmake(0,0,480,320)]; [sprite setcolor:ccc3(255,128,0)];</code>

值这个例子中,我们使用这个技术创建了一个简单的草地和天空背景。

给sprites上色

在之前的小节中我们使用带颜色的矩形绘制了简单的草地和天空背景。能够设置纹理颜色和透明度的是一个简单工具,如果巧妙运用的话可以创造出非常酷的效果。在本小节中我们将创建两个武士各自拿着一个发光武士刀对峙的场景。

cocos2d-x与精灵共舞

请参考recipecollection01工程的代码并注意一些为简洁而删除的代码。

如何做?

<code>//add a sinister red glow gradient behind the evil samurai ccgradientlayer *redgradient = [ccgradientlayer layerwithcolor:ccc4(0,0,0,0) tocolor:ccc4(255,0,0,100) withdirection :ccgradientdirectiont_b width:200 height:200]; [redgradient setposition:ccp(280,60)]; [redgradient setrotation:-90]; [self addchild:redgradient z:2 tag:tag_red_gradient];</code>

// make the swords glow

[self glowat:ccp(230,280) withscale:cgsizemake(3.0f, 11.0f)

withcolor:ccc3(0,230,255) withrotation:45.0f withsprite:goodsamurai];

[self glowat:ccp(70,280) withscale:cgsizemake(3.0f, 11.0f)

withcolor:ccc3(255,200,2) withrotation:-45.0f withsprite:evilsamurai];

-(void) initbuttons {

[ccmenuitemfont setfontsize:16];

//’fade to black’ button

ccmenuitemfont* fadetoblack = [ccmenuitemfont itemfromstring:@

"fade to black" target:self selector:@selector(fadetoblackcallback:)];

ccmenu *fadetoblackmenu = [ccmenu menuwithitems:fadetoblack, nil];

fadetoblackmenu.position = ccp( 180 , 20 );

[self addchild:fadetoblackmenu z:4 tag:tag_fade_to_black];

/* fade the scene to black */

-(void) fadetoblackcallback:(id)sender {

ccsprite *fadesprite = [self getchildbytag:tag_fade_sprite];

[fadesprite stopallactions];

[fadesprite setcolor:ccc3(0,0,0)];

[fadesprite setopacity:0.0f];

[fadesprite runaction:

[ccsequence actions:[ccfadein actionwithduration:2.0f], [ccfadeout

actionwithduration:2.0f], nil] ];

/* create a glow effect */

-(void) glowat:(cgpoint)position withscale:(cgsize)size

withcolor:(cccolor3b)color withrotation:(float)rotation

withsprite:(ccsprite*)sprite {

ccsprite *glowsprite = [ccsprite spritewithfile:@"fire.png"];

[glowsprite setcolor:color];

[glowsprite setposition:position];

[glowsprite setrotation:rotation];

[glowsprite setblendfunc: (ccblendfunc) { gl_one, gl_one }];

[glowsprite runaction: [ccrepeatforever actionwithaction:

[ccsequence actions:[ccscaleto actionwithduration:0.9f

scalex:size.width scaley:size.height], [ccscaleto

actionwithduration:0.9f scalex:size.width*0.75f scaley:size.

height*0.75f], nil] ] ];

[ccsequence actions:[ccfadeto actionwithduration:0.9f

opacity:150], [ccfadeto actionwithduration:0.9f opacity:255], nil] ]

];

[sprite addchild:glowsprite];

它是如何工作的?

本小节展示了一些基本的色彩处理技术。

设置sprite颜色

设置sprite颜色的最简单的的方法如下:

<code>-(void) setcolor:(cccolor3b)color;</code>

设置sprite颜色有效减少了你可以显示的颜色,但是它允许在绘制的时候提供更多的编程灵活性。在本节中我们使用setcolor设置了很多东西,只用它画了一个蓝色的天空,一个黄色的太阳,一个黑色的戏剧电影显示条,cccolor3b是一个c结构,它包含了3个glubyte变量。使用如下的代码创建一个ccclor3b结构:

<code>cccolor3b ccc3(const glubyte r, const glubyte g, const glubyte b);</code>

cocos2d也定义了一系列的预定义的常量颜色,它们是:

<code>ccwhite, ccyellow, ccblue, ccgreen, ccred, ccmagenta, ccblack, ccorange, ccgray</code>

过渡到一个颜色

让场景过渡到一个指定的颜色,我们可以使用一个blank.png技术,在最后我们将介绍它。我们首先绘制一个和场景一样大的sprite,然后将其填充我们要过渡的目标颜色,然后执行ccfadin动作将sprite过渡到这个颜色。

<code>[fadesprite setcolor:ccc3(255,255,255)]; [fadesprite setopacity:0.0f]; [fadesprite runaction: [ccfadein actionwithduration:2.0f] ];</code>

使用ccgradienlayer

使用ccgradienlayer类我们可以创建渐变效果。让背景中的山过渡到两个武士站在的草地,我们可以使用如下代码来实现渐变过渡:

<code>ccgradientlayer *gradientlayer = [ccgradientlayer layerwithcolor :ccc4(61,33,62,255) tocolor:ccc4(65,89,54,255) withdirection:ccgra dientdirectiont_b width:480 height:100]; [gradientlayer setposition:ccp(0,50)]; [self addchild:gradientlayer z:0 tag:tag_ground_gradient];</code>

因为ccgradienlayer同样可以控制透明度,这个功能很有用。正如你看到的,那个邪恶的武士背后是发红光的。

让sprite发光:为了让demo中的刀发光我们使用巧妙的颜色操作,加上混合,调和和缩放动作。首先加载cocos2d提供的fire.png。通过改变它x和y方向尺寸,我们可以让其变瘦或者变胖。如果你想改变其纵横比(因为例子中的纵横比是3:11,已经很瘦了),你可以将其缩放的更生动些。你同样需要设置混合函数{gl_one,gl_one}添加混合。最后这个sprite的效果添加到真实的sprite上。

<code>ccsprite *glowsprite = [ccsprite spritewithfile:@"fire.png"]; [glowsprite setcolor:color]; [glowsprite setposition:position]; [glowsprite setrotation:rotation]; [glowsprite setblendfunc: (ccblendfunc) { gl_one, gl_one }]; [glowsprite runaction: [ccrepeatforever actionwithaction: [ccsequence actions:[ccscaleto actionwithduration:0.9f scalex:size.width scaley:size.height], [ccscaleto actionwithduration:0.9f scalex:size.width*0.75f scaley:size. height*0.75f], nil] ] ]; [glowsprite runaction: [ccrepeatforever actionwithaction: [ccsequence actions:[ccfadeto actionwithduration:0.9f opacity:150], [ccfadeto actionwithduration:0.9f opacity:255], nil] ] ]; [sprite addchild:glowsprite];</code>

sprite的动画

现在给sprite添加动画,这里要强调的是动画的复杂度和你制作动画的难度差不多。在本节中,我们将使用简单的动画创建一个引人入胜的效果。我们创建一群蝙蝠飞向一个让人惊悚的城堡。并使用之前介绍的技术添加一个冷色调的光照效果。

开始

请参考recipecollection01工程的代码,并注意遗漏的部分的代码。

<code>//simpleanimobject.h @interface simpleanimobject : ccsprite { int animationtype; cgpoint velocity; }</code>

@interface ch1_animatingsprites {

nsmutablearray *bats;

ccanimation *batflyup;

ccanimation *batglidedown;

ccsprite *lightningbolt;

ccsprite *lightningglow;

int lightningremovecount;

-(cclayer*) runrecipe {

//add our plist to the spriteframecache

[[ccspriteframecache sharedspriteframecache]

addspriteframeswithfile:@”simple_bat.plist”];

//add a lightning bolt

lightningbolt = [ccsprite spritewithfile:@"lightning_bolt.png"];

[lightningbolt setposition:ccp(240,160)];

[lightningbolt setopacity:64];

[lightningbolt retain];

//add a sprite to make it light up other areas.

lightningglow = [ccsprite spritewithfile:@"lightning_glow.png"];

[lightningglow setcolor:ccc3(255,255,0)];

[lightningglow setposition:ccp(240,160)];

[lightningglow setopacity:100];

[lightningglow setblendfunc: (ccblendfunc) { gl_one, gl_one }];

[lightningbolt addchild:lightningglow];

//set a counter for lightning duration randomization

lightningremovecount = 0;

//bats array initialization

bats = [[nsmutablearray alloc] init];

//add bats using a batch node.

ccspritebatchnode *batch1 = [ccspritebatchnode

batchnodewithfile:@"simple_bat.png" capacity:10];

[self addchild:batch1 z:2 tag:tag_bats];

//make them start flying up.

for(int x=0; x //create simpleanimobject of bat

simpleanimobject *bat = [simpleanimobject

spritewithbatchnode:batch1 rect:cgrectmake(0,0,48,48)];

[batch1 addchild:bat];

[bat setposition:ccp(arc4random()%400+40, arc4random()%150+150)];

//make the bat fly up. get the animation delay (flappingspeed).

float flappingspeed = [self makebatflyup:bat];

//base y velocity on flappingspeed.

bat.velocity = ccp((arc4random()%1000)/500 + 0.2f, 0.1f/

flappingspeed);

//add a pointer to this bat object to the nsmutablearray

[bats addobject:[nsvalue valuewithpointer:bat]];

[bat retain];

//set the bat’s direction based on x velocity.

if(bat.velocity.x &gt; 0){

bat.flipx = yes;

//schedule physics updates

[self schedule:@selector(step:)];

-(float)makebatflyup:(simpleanimobject*)bat {

ccspriteframecache * cache = [ccspriteframecache

//randomize animation speed.

float delay = (float)(arc4random()%5+5)/80;

ccanimation *animation = [[ccanimation alloc] initwithname:@

“simply_bat_fly” delay:delay];

//randomize animation frame order.

int num = arc4random()%4+1;

for(int i=1; i [animation addframe:[cache spriteframebyname:[nsstring

stringwithformat:@"simple_bat_0%i.png",num]]];

num++;

if(num &gt; 4){ num = 1; }

//stop any running animations and apply this one.

[bat stopallactions];

[bat runaction:[ccrepeatforever actionwithaction: [ccanimate

actionwithanimation:animation]]];

//keep track of which animation is running.

bat.animationtype = bat_flying_up;

return delay; //we return how fast the bat is flapping.

-(void)makebatglidedown:(simpleanimobject*)bat {

//apply a simple single frame gliding animation.

“simple_bat_glide” delay:100.0f];

[animation addframe:[cache spriteframebyname:@"simple_bat_01.png"]];

bat.animationtype = bat_gliding_down;

-(void)step:(cctime)delta {

cgsize s = [[ccdirector shareddirector] winsize];

for(id key in bats){

//get simpleanimobject out of nsarray of nsvalue objects.

simpleanimobject *bat = [key pointervalue];

//make sure bats don’t fly off the screen

if(bat.position.x &gt; s.width){

bat.velocity = ccp(-bat.velocity.x, bat.velocity.y);

bat.flipx = no;

}else if(bat.position.x bat.velocity = ccp(-bat.velocity.x, bat.velocity.y);

}else if(bat.position.y &gt; s.height){

bat.velocity = ccp(bat.velocity.x, -bat.velocity.y);

[self makebatglidedown:bat];

}else if(bat.position.y bat.velocity = ccp(bat.velocity.x, -bat.velocity.y);

[self makebatflyup:bat];

//randomly make them fly back up

if(arc4random()%100 == 7){

if(bat.animationtype == bat_gliding_down){ [self

makebatflyup:bat]; bat.velocity = ccp(bat.velocity.x, -bat.

velocity.y); }

else if(bat.animationtype == bat_flying_up){ [self

makebatglidedown:bat]; bat.velocity = ccp(bat.velocity.x, -bat.

//update bat position based on direction

bat.position = ccp(bat.position.x + bat.velocity.x, bat.position.y

+ bat.velocity.y);

//randomly make lightning strike

if(arc4random()%70 == 7){

if(lightningremovecount [self addchild:lightningbolt z:1 tag:tag_lightning_bolt];

lightningremovecount = arc4random()%5+5;

//count down

lightningremovecount -= 1;

//clean up any old lightning bolts

if(lightningremovecount == 0){

[self removechildbytag:tag_lightning_bolt cleanup:no];

它是图和工作的?

本节将介绍使用simpleanimobject构造一个基本的动画类:

动画对象类的结构:

当一个动画转向另一个动画时,记录动画对象的状态是很重要的一个工作。在本例子中,我们使用simpleanimobject,它保存了随意的animationtype的变量。我们同样保存了一个速度变量,它有一个y值,此值和动画帧的延迟成反比:

<code>@interface simpleanimobject : ccsprite { int animationtype; cgpoint velocity; }</code>

根据动画系统的深度,你同样需要保存更多的信息,比如指向一个正在执行的ccanimation实例的指针,帧信息,和物理形状。

更多….

当你越来越深入学习cocos2d游戏开发,你将会变得越来越倾向于使用assynchronous action来实现游戏的逻辑和人工智能。从ccaction这个类继承的类,任何移动的动作都可以使用ccmoveby来实现ccnode的移动,实现ccsprite动画可以使用ccanimation。当动作执行时,一个异步的定时机制保留在了后台中。刚开始程序员通常会过度依赖这个功能。当执行多动作时使用这个技术可以提高效率。在下面的例子中我们将使用一个整合计时器,它将允许我们

控制光照在屏幕上持续的时间。

<code>//randomly make lightning strike if(arc4random()%70 == 7){ if(lightningremovecount [self addchild:lightningbolt z:1 tag:tag_lightning_bolt]; lightningremovecount = arc4random()%5+5; } }</code>

就前面这段代码来说,通常使用同步计时器较异步计时器更胜一筹,记住这个,特别是当你的游戏规模越来越大时。

总结:

在本文中我们简单介绍了sprites的基本使用方法。

继续阅读