어제에 이어 오늘 포스트는 sprite에 대한 Effect Action에 대한 주제이다. 
즉, 우리가 게임중이든 어떠한 목적을 가지는 어플에서 이미지를 사용할때, 그 이미지에 특별한 효과를 주고 싶을때 cocos2d를 사용하지 않는 다면, 직접 openGL을 사용하여 모핑 효과라던지, 여러가지 효과를 줘야 하는데, 그걸 개발자가 사용하기 쉽게 cocos2d에서는 API로 제공하고 있다.

어제 만든 예제를 중, HelloWorldLayer에다른 이미지를 넣어서 cocos2d에서 제공하는 모든 Effect Action을 한번 사용해 보자.

이번에는 BlueOcean의 메인 캐릭터인 거북군이 등장한다.

21가지의 effect들을 모두 테스트 해본결과, cocos2d에서는 3d effect들은 정상적으로 나오지 않는것 같다. 이부분은 depth버퍼등을 조절하여 확인하였으나, 이쁘게 나오지 않는다, 대신 2D전용 effect들은 확실히 쓰임새가 많을것같다.

바로 소스 첨부한다.

수정이 필요한 부분은 appdelegate에서 EAGL설정해주는 부분이 있는데, 1.0 부터는 depth버퍼와 pixel color타입을 이때 바로 생성해주어여 한다.아래와 같이 코드를 수정하자,

아래 굵은 부분을 잘 확인하고 수정해야, effect를 줄때 해당 sprite만 컨트롤이 가능하다.
 

//

//  AppDelegate.m

// 


#import "cocos2d.h"



@implementation AppDelegate


@synthesize window;



- (void) applicationDidFinishLaunching:(UIApplication*)application

{

// Init the window

window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Try to use CADisplayLink director

// if it fails (SDK < 3.1) use the default director

if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )

[CCDirector setDirectorType:kCCDirectorTypeDefault];

CCDirector *director = [CCDirector sharedDirector];

// Init the View Controller

viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];

viewController.wantsFullScreenLayout = YES;

//

// Create the EAGLView manually

//  1. Create a RGB565 format. Alternative: RGBA8

// 2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition

//

//

EAGLView *glView = [EAGLView viewWithFrame:[window bounds]

           pixelFormat:kEAGLColorFormatRGBA8

   depthFormat:GL_DEPTH_COMPONENT16_OES

];

// attach the openglView to the director

[director setOpenGLView:glView];

// // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices

// if( ! [director enableRetinaDisplay:YES] )

// CCLOG(@"Retina Display Not supported");

//

// VERY IMPORTANT:

// If the rotation is going to be controlled by a UIViewController

// then the device orientation should be "Portrait".

//

// IMPORTANT:

// By default, this template only supports Landscape orientations.

// Edit the RootViewController.m file to edit the supported orientations.

//

#if GAME_AUTOROTATION == kGameAutorotationUIViewController

[director setDeviceOrientation:kCCDeviceOrientationPortrait];

#else

[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];

#endif

[director setAnimationInterval:1.0/60];

[director setDisplayFPS:NO];

// make the OpenGLView a child of the view controller

[viewController setView:glView];

// make the View Controller a child of the main window

[window addSubview: viewController.view];

[window makeKeyAndVisible];

// Default texture format for PNG/BMP/TIFF/JPEG/GIF images

// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565

// You can change anytime.

[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

 

   

// Removes the startup flicker

[self removeStartupFlicker];

// Run the intro Scene

[[CCDirector sharedDirector] runWithScene: [HelloWorldLayer scene]];

}

 
 

이렇게 하면, 일단 openGL설정은 다 끝났다. 이제 helloWorldLayer로 가서, 이펙트들을 하나씩 다 사용해보자.
구글을 뒤져보거나 하면 각 effect들을 사용하는 샘플 코드가 몇개 나오지 않는다. 본 포스트에서는 cocos2d 1.0이 제공하는 모든 effect들 21가지의 샘플 코드를 모두 작성하여 아래와 같이 만들어보았다.


일단 sprite 의 effect들은 action을 정의 한후, sprite의 runAction메소드를 사용하여 효과를 줄수 있다. 
 

//

//  HelloWorldLayer.h

//  

//



// When you import this file, you import all the cocos2d classes

#import "cocos2d.h"


// HelloWorldLayer

@interface HelloWorldLayer : CCLayer

{

    CCSprite *turtleSprite;  // 거북군을 위한 sprite, 모든 효과를 여기에 준다.

    CCLabelTTF* effectlabel;

    CGSize size;

    id effectAction; // --> effect들을 정의하는 action을 저장함.


}


// returns a CCScene that contains the HelloWorldLayer as the only child

+(CCScene *) scene;


@end

 
 

지난 예제에서는 매번 label을 생성하고 계속 child로 추가하였는데, 이렇게 하면 나중에 메모리 부족 문제가생길수 있다. 
그래서 이번예제에서는 하나만 생성하고, 해당 문자열을 업데이트 하는 구조로 변경하였다. 

배경이미지를 하나 정해서 뿌려주고, 거북군을 올려준다.
 

//

//  HelloWorldLayer.m

//  cocos2dTest

//

//  Created by Yongsu Kim on 11. 7. 11..

//  Copyright iinov.com 2011. All rights reserved.

//



// Import the interfaces

#import "HelloWorldLayer.h"


#define EFFECT_MAX          21


//static int transitionIndex=0;

static int effectIndex=0;


// HelloWorldLayer implementation

@implementation HelloWorldLayer

+(CCScene *) scene

{

// 'scene' is an autorelease object.

CCScene *scene = [CCScene node];

// 'layer' is an autorelease object.

HelloWorldLayer *layer = [HelloWorldLayer node];

// add layer as a child to scene

[scene addChild: layer];

// return the scene

return scene;

}


-(id) init

{

// always call "super" init

// Apple recommends to re-assign "self" with the "super" return value

if( (self=[super init])) {       

        self.isTouchEnabled = YES;  

        effectAction = nil;

        

        // ask director the the window size

        size = [[CCDirector sharedDirector] winSize];

        

        //bg sprite

        

        CCSprite *sprite=[CCSprite spriteWithFile:@"scenario01.png"];

        

        sprite.anchorPoint = CGPointZero;                        

        

        [sprite setPosition: ccp(0, 0)];

        [self addChild:sprite z:1 tag:1];

        

        //turtleSprite = sprite;

        

        turtleSprite = [CCSprite spriteWithFile:@"turtle1.png"];

        

                              

        

        [turtleSprite setPosition: ccp( size.width /2 , size.height/2 )];

        [self addChild:turtleSprite z:1 tag:1];

                

        CCLabelTTF* label= [CCLabelTTF labelWithString:@"coolkim.tistory.com" fontName:@"AppleGothic" fontSize:24];

        

        

        // position the label on the center of the screen

        label.positionccp( size.width /2 , size.height/6 );

        //[label setVisible:NO];

        // add the label as a child to this Layer

        [self addChild: label z:16 tag:2];    

        

        

        effectlabel= [CCLabelTTF labelWithString:@"Touch to play" fontName:@"AppleGothic" fontSize:24];

        effectlabel.positionccp( size.width /2 , size.height/4 );

        //[effectlabel setVisible:NO];

        // add the label as a child to this Layer

        [self addChild: effectlabel z:2 tag:2];


}

return self;

}

 


터치 입력이 완료될때, 즉, touch up일경우에 효과를 무한 반복으로보여주고, 다음 효과로 넘어간다. 
아래의 샘플 코드를 응용하여, 여러가지 효과를 조합해서 사용할수도 있다. 이부분은 action  부분만 따로 주제를 다룰때 다시 이야기 하도록 하자.
 

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {

    CGPoint location = [touch locationInView: [touch view]];

    

CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

NSLog(@"ccTouchEnded : %f , y : %f",convertedLocation.x ,convertedLocation.y);


    effectAction=nil;

    switch (effectIndex)

    {

        case 0:

            [effectlabel setString:@"CCFlipX3D"];

            effectAction = [CCFlipX3D actionWithDuration:1.0f];

            break;

            

        case 1:

            [effectlabel setString:@"CCFlipY3D"]; 

            effectAction = [CCFlipY3D actionWithDuration:1.0f];

            break;

            

        case 2:

            [effectlabel setString:@"CCLens3D"];

            effectAction = [CCLens3D actionWithPosition:ccp(size.width/2,size.height/2) radius:240 grid:ccg(15,10) duration:1.0f];

            break;

            

        case 3:

            [effectlabel setString:@"CCLiquid"];   

            effectAction = [CCLiquid actionWithWaves:40 amplitude:37 grid:ccg(6, 33) duration:200];

            break;

            

        case 4:

            [effectlabel setString:@"CCRipple3D"]; 

            effectAction = [CCRipple3D actionWithPosition:turtleSprite.position radius: size.width/2 waves:2 amplitude:10 grid:ccg(50,50) duration:5];

            break;

            

        case 5:

            [effectlabel setString:@"CCShaky3D"];

            effectAction = [CCShaky3D actionWithRange:4 shakeZ:NO grid:ccg(15,10) duration:5];

            break;

            

        case 6:

            [effectlabel setString:@"CCTwirl"];

            effectAction = [CCTwirl actionWithPosition:turtleSprite.position twirls:10 amplitude:10 grid:ccg(50,50) duration:10 ];

            break;

            

        case 7:

            [effectlabel setString:@"CCWaves"];

            effectAction = [CCWaves actionWithWaves:5 amplitude:20 horizontal:YES vertical:NO grid:ccg(15,10) duration:5];

            break;

            

        case 8:

            [effectlabel setString:@"CCWaves3D"];  

            effectAction = [CCWaves3D actionWithWaves:18 amplitude:15 grid:ccg(15,10) duration:10];

            break;

            

        case 9:

            [effectlabel setString:@"CCFadeOutBLTiles"];

            effectAction = [CCFadeOutBLTiles actionWithSize:ccg(50,50) duration:5];

            break;

            

        case 10:

            [effectlabel setString:@"CCFadeOutTRTiles"];

            effectAction = [CCFadeOutTRTiles actionWithSize:ccg(50,50) duration:5];

            break;

            

        case 11:

            [effectlabel setString:@"CCFadeOutUpTiles"];

            effectAction = [CCFadeOutUpTiles actionWithSize:ccg(50,50) duration:5];

            break;

            

        case 12:

            [effectlabel setString:@"CCFadeOutDownTiles"];

            effectAction = [CCFadeOutDownTiles actionWithSize:ccg(50,50) duration:5];

            break;

            

        case 13:

            [effectlabel setString:@"CCJumpTiles3D"];

             effectAction = [CCJumpTiles3D actionWithJumps:2 amplitude:10 grid:ccg(50,50) duration:5];

            break;

            

        case 14:

            [effectlabel setString:@"CCShakyTiles3D"];

            effectAction = [CCShakyTiles3D actionWithRange:2 shakeZ:NO grid:ccg(50,50) duration:5 ];

            break;

            

        case 15:

            [effectlabel setString:@"CCShatteredTiles3D"];

            effectAction = [CCShatteredTiles3D actionWithRange:10 shatterZ:NO grid:ccg(50,50) duration:5 ];

            break;

            

        case 16:

            [effectlabel setString:@"CCShuffleTiles"];

            effectAction = [CCShuffleTiles actionWithSeed:2 grid:ccg(50,50) duration:5];

            break;

            

        case 17:

            [effectlabel setString:@"CCSplitCols"];

            effectAction = [CCSplitCols actionWithCols:4 duration:5];

            break;

            

        case 18:

            [effectlabel setString:@"CCSplitRows"];

            effectAction = [CCSplitRows actionWithRows:4 duration:5];

            break;

            

        case 19:

            [effectlabel setString:@"CCTurnOffTiles"];

            effectAction = [CCTurnOffTiles actionWithSeed:2 grid:ccg(50,50) duration:5];

            break;

            

        case 20:

            [effectlabel setString:@"CCWavesTiles3D"];

            effectAction = [CCWavesTiles3D actionWithWaves:5 amplitude:10 grid:ccg(50,50) duration:5];

            break;

            

    }

    


    effectIndex++;

    

    if(effectIndex == EFFECT_MAX)

        effectIndex=0;

    

    if(effectAction != nil)

    {

        [turtleSprite stopAllActions]; // 이전의 효과는 모두 종료시키고.

        [turtleSprite runAction: [CCRepeatForever actionWithAction: effectAction]]; //새로운 효과를 실행한다.

    }

}

 


아래 동영상은 위의 예제를 실행시킨 화면을 캡쳐한 것이다. 보는것과 같이 3D 효과는 잘 먹지 않는다. 이부분은 확인해보고, 어떻게 하면 잘나오는지 수정방법을 찾으면 업데이트 하도록 하겠다. 


다음 포스트는 터치 이벤트를 처리해서, 스프라이트를 이동하는 법에 대해서 이야기하겠다. 게임을 만들면 캐릭터들을 콘트롤 하는 방법에 대한 주제이다.
 

'코딩하고 > iOS' 카테고리의 다른 글

iOS용 게임 개발기 -8-  (0) 2011.08.20
iOS용 게임 개발기 -6-  (0) 2011.08.17
VoodooHDA 64비트 빌드 그리고, nVidia HDMI 제거.  (2) 2011.08.15
iOS용 게임 개발기 -5-  (0) 2011.08.10
iOS용 게임 개발기 -4.1-  (0) 2011.08.02
블로그 이미지

커뉴

이 세상에서 꿈 이상으로 확실한 것을, 인간은 가지고 있는 것일까?

,