====== Hello Events ======
//cocos2d v0.8-beta 또는 그 이후 버전에 적용됩니다.//
{{wiki:hello_events.jpg}}
**주의:**
이 예제는 단순히 스크린에 라벨을 렌더링하는 기본 단계를 보여줄 뿐입니다.
초기화를 수행하는 다른 옵션들은 설명을 단순화하기 위해 이 예제에서는 설명하지 않을 것입니다.
===== 구현 파일 =====
**File**: [[http://code.google.com/p/cocos2d-iphone/source/browse/trunk/tests/samples/HelloEvents.m|HelloEvents.m]]
objective-c에서 구현체는 //.m// 파일에 있고, 인터페이스는 //.h// 파일에 정의됩니다.
==== Import Headers ====
c / c++ / java / 기타와 같이 헤더를 임포트합니다.
// UIWindow, NSAutoReleasePool, 다른 객체를 사용하기 때문에
#import
// 인터페이스 임포트
#import "HelloEvents.h" //Fix here
// 간단한 태그 하나 선언
enum {
kTagSprite = 1,
};
==== 레이어 ====
The //magic// occurs in the class. 이번에는 //Label// 과 //Sprite// 두 객체를 포함하는 //Layer//를 생성할 겁니다.
* Touches: 이 스프라이트는 터치된 점으로 이동하게 됩니다.
* Accelerometer: 이 스프라이트는 가속도센서에 따라 변하게 됩니다.
@implementation HelloEvents
// 인스턴스 초기화 "init"
-(id) init
{
// 항상 "super" init 호출하셔야 합니다.
// 애플은 "super"의 리턴값을 "self"에 할당하는 것을 권장합니다.
if( (self=[super init] )) {
// isTouchEnabled는 상속된 레이어 클래스의 속성입니다.
// YES일 때 터치 이벤트가 동작합니다.
self.isTouchEnabled = YES;
// isAccelerometerEnabled는 상속된 레이어 클래스의 속성입니다.
// YES일 때 가속도센서 이벤트가 동작합니다.
self.isAccelerometerEnabled = YES;
//
// Label
//
// 라벨 생성 및 초기화
CCLabel* label = [Label labelWithString:@"Hello Events" fontName:@"Marker Felt" fontSize:64];
// 디렉터에 윈도우 사이즈를 알아본다.
CGSize size = [[CCDirector sharedDirector] winSize];
// 스크린의 한 가운데에 라벨을 위치시킨다.
// "ccp"는 한 점을 생성하는 헬퍼 매크로 입니다. "CoCos Point"를 뜻하죠.
label.position = ccp( size.width /2 , size.height/2 );
// 본 레이어의 자손으로 라벨 추가
[self addChild: label];
//
// Sprite
//
CCSprite *sprite = [CCSprite spriteWithFile:@"grossini.png"];
sprite.position = ccp( 50, 50);
// z는 z-order 입니다. 더 큰 값이 낮은 값보다 위에 표시됨을 뜻합니다.
// 디폴트 z값은 0입니다.
// 스프라이트에 태그를 추가하면 이후에 태그에 따라 객체를 가져올 수 있습니다.
[self addChild:sprite z:1 tag:kTagSprite];
}
return self;
}
// 할당된 객체들을 릴리즈할 때 "dealloc" 호출
- (void) dealloc
{
// 이번 케이스에는 릴리즈할 필요가 전혀 없는 특별한 예제이므로 dealloc 할 것이 없습니다.
// ocos2d는 자동으로 자손을 릴리즈합니다.(Label)
// "super dealloc" 호출을 잊으시면 안됩니다.
[super dealloc];
}
=== 터치 콜백 ===
아래의 콜백은 //isTouchesEnabled//가 YES이기 때문에 호출되는 것입니다.
가능한 이벤트:
* ccTouchesBegan
* ccTouchesMoved
* ccTouchesEnded
* cctouchesCancelled
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if( touch ) {
CGPoint location = [touch locationInView: [touch view]];
// 중요:
// 터치는 항상 수직 좌표을 사용합니다. 여러분은 올바른 좌표계로 변환하여야 합니다.(역자 주 : 좌상단이 0,0인 Quartz의 좌표계를 말하는 것 같네요. cocos2d는 OpenGL 기반이기 때문에 좌하단이 0,0인 좌표계를 사용할 겁니다. 아마..)
CGPoint convertedPoint = [[Director sharedDirector] convertToGL:location];
CCNode *sprite = [self getChildByTag:kTagSprite];
// 동작하는 모든 액션을 정지
[sprite stopAllActions];
// 그리고 새 동작을 실행
[sprite runAction: [MoveTo actionWithDuration:1 position:convertedPoint]];
// 이 이벤트를 받을 핸들러는 더 이상 없을 겁니다.
}
// 이벤트를 무시합니다. 다른 리시버들은 이 이벤트를 받게 됩니다.(같은 이벤트(터치)는 발생하지만 ccTouchesEnded는 이 이벤트에 더 이상 동작하지 않게 될 거라는 뜻인 것 같습니다.)
}
=== 가속도센서 콜백 ===
아래의 콜백은 //isAccelerometerEnabled//가 YES이기 때문에 호출되는 것입니다.
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
CCNode *sprite = [self getChildByTag:kTagSprite];
// 수직좌표계이기 때문에 수평좌표계로 변환
CGPoint converted = ccp( (float)-acceleration.y, (float)acceleration.x);
// z-rotation상의 위치 업데이트
// 스프라이트는 항상 'standing up'이 될 겁니다.
sprite.rotation = (float) CC_RADIANS_TO_DEGREES( atan2f( converted.x, converted.y) + M_PI );
// 가속도의 증가에 따라서 크기 업데이트
// 가속도를 더 높일 수록 크기는 커집니다.
sprite.scale = 0.5f + sqrtf( (converted.x * converted.x) + (converted.y * converted.y) );
}
@end
==== 어플리케이션 델리게이트 ====
이 클래스는 초기화를 핸들링합니다.
아마 여러분의 모든 게임은 이 어플리케이션 델리게이트와 비슷할겁니다.
아래 코드를 이해하지 못하신다면 당장은 별로 중요하지 않을 겁니다.
@implementation AppController
// window 는 속성입니다. @synthesize 는 조상 메소드를 생성할 겁니다.
@synthesize window;
// 어플리케이션 엔트리 포인트
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
// UIWindow 생성/초기화
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Enable Multiple Touches ? No
[window setMultipleTouchEnabled:NO];
// cocos2d를 window에 붙이고
[[Director sharedDirector] attachInWindow:window];
// 레이어를 생성하기 전에 수평 모드로 셋팅
[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
// 윈도우를 visible로 만들기
[window makeKeyAndVisible];
// 아무것도 없는 Scene 초기화/생성
Scene *scene = [Scene node];
// HelloEvents 레이어 초기화/생성
Layer *layer = [HelloEvents node];
// HelloEvents 레이어를 메인 scene의 자손으로 붙임
[scene addChild:layer];
// Run!
[[Director sharedDirector] runWithScene: scene];
}
- (void) dealloc
{
[window release];
[super dealloc];
}
@end
==== 메인 엔트리 포인트 ====
objective-c도 c / c++ 처럼 메인 엔트리 포인트가 여전히 //main//함수입니다.
int main(int argc, char *argv[]) {
// 보통 아래처럼 그냥 두는게 안전하지요. 이름만 "AppController"로 하는 것 빼고요.
NSAutoreleasePool *pool = [NSAutoreleasePool new];
UIApplicationMain(argc, argv, nil, @"AppController");
[pool release];
return 0;
}
===== 헤더 파일 =====
**File**: [[http://code.google.com/p/cocos2d-iphone/source/browse/trunk/tests/samples/HelloEvents.h|HelloEvents.h]]
// 이 파일을 임포트 할 때 여러분은 모든 cocos2d 클래스를 임포트하게 됩니다.
#import "cocos2d.h"
// 어플리케이션 델리게이트 클래스
@interface AppController : NSObject
{
// main UIWindow
// OpenGL 뷰는 UIWindow의 뷰가 됩니다.
UIWindow *window;
}
// 메인 UIWindow를 속성으로 만드세요.
@property (nonatomic, retain) UIWindow *window;
@end
// HelloEvents Layer
@interface HelloEvents : Layer
{
}
@end