【cocos2d入門】cocos2dのイベント

Posted by: daichi  /  Category: iphone開発

前回までのcocos2d入門。
【cocos2d入門】cocos2dのアニメーション | iphoneアプリで稼げるのか

前回でcocos2dのアニメーションが終了。
今回はcocos2dでイベント処理します。
ここで使うcocos2dのバージョンは、前回同様cocos2d-0.9.0-alphaです。

Event

イベントとしてユーザからの応答を受け付ける処理の実装の仕方を見て行きます。

イベント部分に関しては、ざっと見てみた限りUIKit系と同じでした。
すなわち、タップと傾き(加速度)です。

タップを検知

cocos2dでタップを検知するのはとても簡単です。
検知してくれるのはCCLayerです。

CCLayerクラスのプロパティisTouchEnabledにYESをセットすればOK。
isTouchEnabledをYESにすると以下のコールバックメソッドが呼ばれるようになります。
  • – (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  • – (BOOL)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  • – (BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  • – (BOOL)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
どこかで見たことがあるメソッド名です。そうです。
UIViewのタップ関連メソッドとほとんど同じです。頭にccがついてるだけです。
# 0.9.0だからついてるのかも。0.8系のものは未確認

なので、特別な説明はここではしません。

傾きを検知

傾き検知も簡単。
CCLayerのisAccelerometerEnabledプロパティにYESをセットすれば検知開始。
YESにすると以下のメソッドが呼ばれます。

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration

これもUIKit系と同じですね。
なので、イベントに関しては特別なことはあまりない感じでした。
サンプルを載せておきます。# といってもcocos2dに含まれるソースのまんまです。

?View Code OBJECTIVE-C
#import <UIKit/UIKit.h>
#import "HelloEvents.h"
 
// A simple 'define' used as a tag
enum {
	kTagSprite = 1,
};
 
// HelloWorld implementation
@implementation HelloEvents
 
// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init] )) {
 
		// isTouchEnabled is an property of Layer (the super class).
		// When it is YES, then the touches will be enabled
		self.isTouchEnabled = YES;
 
		// isTouchEnabled is property of Layer (the super class).
		// When it is YES, then the accelerometer will be enabled
		self.isAccelerometerEnabled = YES;
 
		//
		// CCLabel
		//
 
		// create and initialize a CCLabel
		CCLabel* label = [CCLabel labelWithString:@"Hello Events" fontName:@"Marker Felt" fontSize:64];
 
		// ask director the the window size
		CGSize size = [[CCDirector sharedDirector] winSize];
 
		// position the label on the center of the screen
		// "ccp" is a helper macro that creates a point. It means: "CoCos Point"
		label.position =  ccp( size.width /2 , size.height/2 );
 
		// add the label as a child to this Layer
		[self addChild: label];
 
		//
		// Sprite
		//
 
		CCSprite *sprite = [CCSprite spriteWithFile:@"grossini.png"];
		sprite.position = ccp( 50, 50);
 
		// z is the z-order. Greater values means on top of lower values.
		// Default z value is 0. So the sprite will be on top of the label.
		// Add the sprite with a tag, so we can later 'get' the sprite by this tag
		[self addChild:sprite z:1 tag:kTagSprite];		
	}
	return self;
}
 
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (CCLabel)
 
	// don't forget to call "super dealloc"
	[super dealloc];
}
 
 
// This callback will be called because 'isTouchesEnabled' is YES.
// Possible events:
//   * ccTouchesBegan
//   * ccTouchesMoved
//   * ccTouchesEnded
//   * cctouchesCancelled
- (BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *touch = [touches anyObject];
 
	if( touch ) {
		CGPoint location = [touch locationInView: [touch view]];
 
		// IMPORTANT:
		// The touches are always in "portrait" coordinates. You need to convert them to your current orientation
		CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:location];
 
		CCNode *sprite = [self getChildByTag:kTagSprite];
 
		// we stop the all running actions
		[sprite stopAllActions];
 
		// and we run a new action
		[sprite runAction: [CCMoveTo actionWithDuration:1 position:convertedPoint]];
 
		// no other handlers will receive this event
		return kEventHandled;
	}
 
	// we ignore the event. Other receivers will receive this event.
	return kEventIgnored;
}
 
// This callback will be called because 'isAccelerometerEnabled' is YES.
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{	
	CCNode *sprite = [self getChildByTag:kTagSprite];
 
	// Convert the coordinates to 'landscape' coords
	// since they are always in 'portrait' coordinates
	CGPoint converted = ccp( (float)-acceleration.y, (float)acceleration.x);	
 
	// update the rotation based on the z-rotation
	// the sprite will always be 'standing up'
	sprite.rotation = (float) CC_RADIANS_TO_DEGREES( atan2f( converted.x, converted.y) + M_PI );
 
	// update the scale based on the length of the acceleration
	// the higher the acceleration, the higher the scale factor
	sprite.scale = 0.5f + sqrtf( (converted.x * converted.x) + (converted.y * converted.y) );
}
@end
 
//
// Application Delegate implementation.
// Probably all your games will have a similar Application Delegate.
// For the moment it's not that important if you don't understand the following code.
//
@implementation AppController
 
// window is a property. @synthesize will create the accesors methods
@synthesize window;
 
// Application entry point
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
 
	// Try to use CADisplayLink director
	// if it fails (SDK < 3.1) use Threaded director
	if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] )
		[CCDirector setDirectorType:CCDirectorTypeDefault];
 
	// create an initilize the main UIWindow
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 
	// Enable Multiple Touches ? No
	[window setMultipleTouchEnabled:NO];
 
	// Attach cocos2d to the window
	[[CCDirector sharedDirector] attachInWindow:window];
 
	// before creating any layer, set the landscape mode
	[[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
 
	// Make the window visible
	[window makeKeyAndVisible];
 
	// Create and initialize parent and empty Scene
	CCScene *scene = [CCScene node];
 
	// Create and initialize our HelloEvents Layer
	CCLayer *layer = [HelloEvents node];
	// add our HelloEvents Layer as a child of the main scene
	[scene addChild:layer];
 
	// Run!
	[[CCDirector sharedDirector] runWithScene: scene];
}
 
- (void) dealloc
{
	[window release];
	[super dealloc];
}
 
@end
 
 
//
// main entry point. Like any c or c++ program, the "main" is the entry point
//
int main(int argc, char *argv[]) {
	// it is safe to leave these lines as they are.
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	UIApplicationMain(argc, argv, nil, @"AppController");
	[pool release];
	return 0;
}

cocos2dはドキュメントも豊富で、サンプルコードのコメントも充実してるのでThree20と比べるとだいぶ助かります。

と、今回までで、HelloWorld、アニメーション、イベントが終了したので、
簡単なゲームアプリはこれだけでできてしまいそうです。
五目並べとか、ソリティアとか、イベントを起点に動作が始まるゲームで、
画面遷移を必要としないものなら。

でもそれだと寂しいので、Sceneの切り替わりと、後はSprite(画像)の切り替え、メニューの表示、スレッド処理、当たり判定あたりをやれば、シューティングゲームまで作れそうな予感。

まだまだやることは盛りだくさん。

タグ: cocos2d, チュートリアル, ライブラリ, 入門

関連する投稿

コメント

Get Adobe Flash playerPlugin by wpburn.com wordpress themes