遊戲成品:一開始畫面中間有一個cocod2D的icon,然後你觸碰螢幕的某處,這個icon會移動過去。
首先開啟一個cocos2D的專案,然後建立一個新的class,我是取TowardLayer,繼承自CCLayer。
在TowardLayer.h裡面,改成下列:
然後在TowardLayer.m,改成以下內容。
#import "TowardLayer.h"
@implementation TowardLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
TowardLayer *layer = [TowardLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id)init {
self = [super init];
if (self != nil) {
isTouchEnabled_ = YES;
CGSize winSize = [CCDirector sharedDirector].winSize;
icon = [CCSprite spriteWithFile:@"icon-Small.png"];
icon.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:icon];
}
return self;
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation =
[[CCDirector sharedDirector] convertToGL:touchLocation];
id moveIcon = [CCMoveTo actionWithDuration:1.0f position:touchLocation];
[icon runAction:moveIcon];
}
}
- (void) dealloc
{
[super dealloc];
}
@end
最後一步驟是到AppDelegate.m裡面:
我大概描述一下我寫的心得。
注意,用-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)even;會沒有反應,這讓我很訝異,還以為哪裡寫錯,後改成多點才對。萬一有遇到跟我類似的情況,還是改成多點的吧。
首先開啟一個cocos2D的專案,然後建立一個新的class,我是取TowardLayer,繼承自CCLayer。
在TowardLayer.h裡面,改成下列:
#import "CCLayer.h"
#import "cocos2d.h"
@interface TowardLayer : CCLayer
{
CCSprite *icon;
}
+(CCScene *) scene;
@end
#import "cocos2d.h"
@interface TowardLayer : CCLayer
{
CCSprite *icon;
}
+(CCScene *) scene;
@end
然後在TowardLayer.m,改成以下內容。
#import "TowardLayer.h"
@implementation TowardLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
TowardLayer *layer = [TowardLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id)init {
self = [super init];
if (self != nil) {
isTouchEnabled_ = YES;
CGSize winSize = [CCDirector sharedDirector].winSize;
icon = [CCSprite spriteWithFile:@"icon-Small.png"];
icon.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:icon];
}
return self;
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation =
[[CCDirector sharedDirector] convertToGL:touchLocation];
id moveIcon = [CCMoveTo actionWithDuration:1.0f position:touchLocation];
[icon runAction:moveIcon];
}
}
- (void) dealloc
{
[super dealloc];
}
@end
最後一步驟是到AppDelegate.m裡面:
#import "TowardLayer.h"
.....
....
[[CCDirector sharedDirector] runWithScene: [HelloWorldLayer scene]]; //這行要改掉,改成下面這一行
[[CCDirector sharedDirector] runWithScene:[TowardLayer scene]];
....我大概描述一下我寫的心得。
注意,用-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)even;會沒有反應,這讓我很訝異,還以為哪裡寫錯,後改成多點才對。萬一有遇到跟我類似的情況,還是改成多點的吧。
留言
張貼留言