작업할 파일을 다음과 같습니다.
(1) MenuScene.h
(2) MenuScene.m
(3) GameDemoAppDelegate.m
MenuScene.h
//
// MenuScene.h
// GameDemo
//
// Created by cmpak on 5/7/10.
// Copyright 2010 thefirstgood.com. All rights reserved.
//
//#import <Foundation/Foundation.h>
#import "cocos2d.h"
//@interface MenuScene : NSObject {
@interface MenuScene : CCScene {
}
@end
MenuScene.m
//
// MenuScene.m
// GameDemo
//
// Created by cmpak on 5/7/10.
// Copyright thefirstgood.com. All rights reserved.
//
#import "MenuScene.h"
@implementation MenuScene
// layer에 추가할 때 z-index로 사용됩니다.
enum {
kTagBackground = 0,
kTagMenu = 1
};
- (id) init {
if( (self=[super init]) ) {
// 배경 이미지를 표시하기 위해 Sprite를 이용합니다.
CCSprite *bgSprite = [CCSprite spriteWithFile:@"background.png"];
// anchorPoint는 따로 알아보도록 하겠습니다.
bgSprite.anchorPoint = CGPointZero;
// ccp는 CGPointMake와 같습니다.
[bgSprite setPosition: ccp(0, 0)];
// MenuScene에 배경 Sprite를 Child로 넣습니다. z-index는 0으로 설정합니다.
// 위에 선언된 enum을 참고하세요. 모든 CCNode는 tag를 가질 수 있습니다.
// tag 값을 주게되면 로컬변수를 사용하여 만들어진
// CCNode를 -(CCNode*) getChildByTag:(int)aTag 메소드를 이용하여 찾을 수 있습니다.
[self addChild:bgSprite z:kTagBackground tag:kTagBackground];
// 메뉴버튼을 만듭니다.
// itemFromNormalImage는 버튼이 눌려지기 전에 보여지는 이미지이고,
// selectedImage는 버튼이 눌려졌을 때 보여지는 이미지입니다.
// target을 self로 한 것은 버튼이 눌려졌을 때 발생하는 터치 이벤트를 MeneScene에서
// 처리를 하겠다는 것입니다.
// @selector를 이용하여 버튼이 눌려졌을 때 어떤 메소드에서 처리를 할 것인지 결정합니다.
CCMenuItem* newGameMenuItem = [CCMenuItemImage itemFromNormalImage:@"new_game.png"
selectedImage:@"new_game_s.png"
target:self
selector:@selector(newGameMenuCallback:)];
CCMenuItem* scoreMenuItem = [CCMenuItemImage itemFromNormalImage:@"high_score.png"
selectedImage:@"high_score_s.png"
target:self
selector:@selector(highScoreMenuCallback:)];
CCMenuItem* aboutMenuItem = [CCMenuItemImage itemFromNormalImage:@"about.png"
selectedImage:@"about_s.png"
target:self
selector:@selector(aboutMenuCallback:)];
// 위에서 만들어지 각각의 메뉴 아이템들을 CCMenu에 넣습니다.
// CCMenu는 각각의 메뉴 버튼이 눌려졌을 때 발생하는 터치 이벤트를 핸들링하고,
// 메뉴 버튼들이 어떻게 표시될 것인 지 레이아웃 처리를 담당합니다.
CCMenu *menu = [CCMenu menuWithItems: newGameMenuItem, scoreMenuItem, aboutMenuItem, nil];
// alignItemsVertically 메소드는 자동으로 모든 버튼을 세로로 균일한 스페이스(padding)를 주고
// 정렬을 시킵니다. 만일 여러분이 특정한 픽셀 수치만큼만 스페이스(padding) 주고 싶다면,
// -(void) alignItemsVerticallyWithPadding:(float)padding 메소드를 사용하면 됩니다.
[menu alignItemsVertically];
// 만들어진 메뉴를 배경 sprite 위에 표시합니다.
[self addChild:menu z:kTagMenu tag:kTagMenu];
}
return self;
}
// 메뉴 아이템(버튼)을 만들 때 이벤트 핸들러로 등록된 메소드를 만듭니다.
// 이 예제에서는 콘솔(Console)에 메세지를 보여주는 것으로 대신합니다.
- (void) newGameMenuCallback: (id) sender {
NSLog(@"New Game 버튼이 눌려졌음.");
}
- (void) highScoreMenuCallback: (id) sender {
NSLog(@"High Score 버튼이 눌려졌음");
}
- (void) aboutMenuCallback: (id) sender {
NSLog(@"About 버튼이 눌려졌음");
}
@end
(1) 배경 이미지를 표시하기 위해서 CCSprite를 사용합니다. CCSprite는 cocos2d를 사용하여 그래픽 이미지를 화면에 표시하거나 그 이미지를 움직이고 회전시키는 것과 같은 액션을 줄때 사용되는 클래스입니다. 스프라이트의 앵커포인트는 이미지의 기준점입니다.
(2) 스프라이트를 scene의 자식으로 추가합니다. z-index는 값이 클수록 위로 올라옵니다. 태그를 설정하면 그 객체에 접근할 때 용이합니다.
(3) CCMenuItem클래스로 메뉴버튼을 만듭니다. 버튼의 상태는 보통 상태와 터치 상태. 두 가지 입니다.
(4) CCMenuItem :
가로 정렬 - alignItemsHorizontally, 가로 원하는 공간만큼 정렬 - alignItemsHorizontallyWithPadding
GameDemoAppDelegate.m
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
// Init the window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// cocos2d will inherit these values
[window setUserInteractionEnabled:YES];
[window setMultipleTouchEnabled:YES];
// Try to use CADisplayLink director
// if it fails (SDK < 3.1) use the default director
if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:CCDirectorTypeDefault];
// Use RGBA_8888 buffers
// Default is: RGB_565 buffers
[[CCDirector sharedDirector] setPixelFormat:kPixelFormatRGBA8888];
// Create a depth buffer of 16 bits
// Enable it if you are going to use 3D transitions or 3d objects
// [[CCDirector sharedDirector] setDepthBufferFormat:kDepthBuffer16];
// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
// You can change anytime.
[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
// before creating any layer, set the landscape mode
//[[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
[[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationPortrait];
[[CCDirector sharedDirector] setAnimationInterval:1.0/60];
[[CCDirector sharedDirector] setDisplayFPS:NO];
// create an openGL view inside a window
[[CCDirector sharedDirector] attachInView:window];
[window makeKeyAndVisible];
//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
// MenuScene을 만들어 첫 화면으로 보여준다.
MenuScene *menuScene = [[MenuScene alloc] init];
[[CCDirector sharedDirector] runWithScene:(CCScene*)menuScene];
[menuScene release];
}