【iphone游戏开发】iphone-Cocos2d游戏开发之三:精灵表的详细讲解(二)小鸟眨眼睛

来源:互联网 发布:js获取当前设备 编辑:程序博客网 时间:2024/05/01 19:08

在上一节我们讲了精灵表的一些知识和使用Zwoptex对图片进行了整合和生成plist文件。这一节我们应用上一节的工具重新生成一对精灵表,对精灵进行操作。

1.建立工程

 

建立完工程后,如下:


2.载入文件


分别载入以上4个精灵,利用zwoptex生成的plist和png文件如下:



接下来把生成的plist和png导入resources文件中。

3.编程

在HelloWorld中的.m文件的注释掉里面其他的代码,重写如下:


代码解释如下:

[csharp] view plaincopy
  1. CGSize s = [[CCDirector sharedDirector] winSize];//获取屏幕的尺寸  
  2.           
  3. [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"sprite.plist"];//载入我们生成的plist文件到CCSpriteFrameCache的缓冲文件中  
  4.           
  5. //获取精灵表中的第一张图片加载在场景中,并设置他的位置  
  6. sprite1 = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"sprite_01.png"]];  
  7. sprite1.position = ccp( s.width/2-80, s.height/2);  
  8. [self addChild:sprite1];  
  9.           
  10. //获取精灵表中的第二张图片加载在场景中,并设置他的位置  
  11. sprite2 = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"sprite_03.png"]];  
  12. sprite2.position = ccp( s.width/2+80, s.height/2);  
  13. [self addChild:sprite2];  
  14.           
  15.  //根据设定的时间更新页面。调用updateSprite方法  
  16.  [self schedule:@selector(updateSprite:) interval:0.3f];  


当调用updateSprite方法实现小鸟眨眼睛的更新。

代码的解释如下:

[csharp] view plaincopy
  1. static int sprite1FrameIndex = 0;//标志位置为0  
  2. static int sprite2FrameIndex = 4;//标志位置为4  
  3. -(void) updateSprite:(ccTime)dt  
  4. {  
  5.       
  6.     if (++ sprite1FrameIndex > 2) {  
  7.         sprite1FrameIndex = 1;//进行循环。使精灵1不断执行相同的过程  
  8.     }  
  9.     if (++ sprite2FrameIndex > 4) {  
  10.         sprite2FrameIndex = 3;//进行循环。使精灵2不断执行相同的过程  
  11.     }  
  12.     //更新的时候显示其他的精灵图片。  
  13.     [sprite1 setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"sprite_%02d.png",sprite1FrameIndex]]];  
  14.     [sprite2 setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"sprite_%02d.png",sprite2FrameIndex]]];  
  15. }  



4.运行如下图


5.总结

这一节的重点在于如何对上一节生成的文件进行读取并做成动画效果显示,其中,CCSpriteFrameCache和setDisplayFrame这两个方法较为重要,可以重点掌握一下,以便能够熟练的应用在日常的游戏开发项目中。

源代码下载如下:http://download.csdn.net/detail/qiaoshe/3707533


转自:http://blog.csdn.net/qiaoshe/article/details/6896235

原创粉丝点击