原文链接:http://iphonedev.net/2009/05/10/cocos2d-example-move-sprite/
(注:原文写的较早,与现在的版本有点出入,这里我直接换成目前版本)
Cocos2d 引擎大大的简化了iphone游戏开发的过程。在这个实例中,我们将用一个红色的小方块图片做为精灵,当我们触摸屏幕时,精灵将会平滑的移动到触摸处,在开始这篇教程之前,我们首先需要确定Cocos2d 的环境已经建立起来。为了简化这个过程,你可以下载Coco2d 0.7.2(目前最新版本1.0.0)项目模版,并且安装到合适的位置
步骤1:创建一个Cocos2d 项目,如果你已经正确安装的cocos2d项目模板,你会看到如下图所示的选项
选择 cocos2d Application 然后为工程命名“BoxMove”
步骤2:添加这个图片到 Resources
1 #import"cocos2d.h"2 3 #import"Layer.h"4 5 @interfaceBoxLayer : Layer { CCSprite*boxSprite; } @end6 7 //BoxLayer.m8 9 #import"BoxLayer.h"10 11 @implementationBoxLayer
12 13 -(id)init{
14 self =[super init];
15 if(nil!=self){
16 isTouchEnabled =YES;
17 boxSprite =[CCSprite spriteWithFile:@"box.png"];
18 [boxSprite setPosition:CGPointMake(25, 25)];
19 [self add:boxSprite];
20 }
21 returnself;
22 }
23 24 -(BOOL) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *) event25 {
26 UITouch *touch =[touches anyObject];
27 CGPoint point =[touch locationInView: [touch view]];
28 [boxSprite runAction:[CCMoveTo actionWithDuration:1position:[[Director sharedDirector]convertToGL:point]]];
29 returnYES;
30 }
31 @end
在BoxLayer类的init方法中 我们创建了一个box.png的精灵对象 并且设置了它的初始位置,(注意:我们在BoxLayer类中定义了一个精灵指针 boxSprite,在init方法最后去初始化)此外,我们实现了ccTouchesBegan:withEvent 方法,这就以为着这个视图层将会响应触摸事件,在这个方法里,我们首先得到了触摸的位置,然后我们用 runAction 方法将精灵移动到此,需要注意的是 convertCoordinate 方法(目前使用convertToGL) 将UIKit 坐标转换成了cocos2d坐标(注意:触摸事件使用的是 UIKIT坐标,与cocos2d坐标不同)
步骤4:工程模版会默认创建一个MyScene 类(新的版本中为HelloWorldLayer),但我们需要做以下修改:
//HelloWorldLayer.h#import"Cocos2d.h"#import"BoxLayer.h"@interfaceHelloWorldLayer: CCLayer {
BoxLayer*boxLayer;
}
@property (nonatomic, retain) BoxLayer*boxLayer;
@end//HelloWorldLayer.m#import"HelloWorldLayer.h"#import"BoxLayer.h"@implementationHelloWorldLayer
@synthesizeboxLayer;
-(void)dealloc{
[boxLayer release];
[super release];
}
-(id)init{
self =[super init];
if(nil !=self){
self.boxLayer =[[BoxLayer alloc]init];
[self add:boxLayer];
}
returnself;
}
@end
在以上的代码中,我们在HelloWorldLayer类中定义了一个BoxLayer的指针boxLayer ,并在init方法中为它分配了内存,在最后,我们把boxLayer 添加到屏幕上.(注:要在dealloc中释放内存)
步骤5:构建工程并运行,你将会看到如下的运行结果