cocos2d-x 3.0이상에서 라벨사용시 폰트 자간 조절 하는 법



CCLabel.cpp


CCLabel.h


CCLabelTextFormatter.cpp


위3가지의 파일을 덮어 씌어 준 후 사용 하면 됩니다. 혹시 버젼이 변경 되어 다른 곳에서 에러가 날 시 


CCLabe.cpp 에 추가 Code


, _additionalKerning(0.0f)


void Label::setAdditionalKerning(float space)

{

    CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");

    if (_additionalKerning != space)

    {

        _additionalKerning = space;

        _contentDirty = true;

    }

}


float Label::getAdditionalKerning() const

{

    CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");

    

    return _additionalKerning;

}


CCLabel.h 에 추가 Code


    float _additionalKerning;


    void setAdditionalKerning(float space);

    /** Returns the additional kerning of this label

    @warning Not support system font

    @since v3.2.0

    */

    float getAdditionalKerning() const;


CCLabelTextFormatter.cpp 에 변경 Code

nextFontPositionX += charAdvance + kernings[i];

위 코드를 아래와 같이 변경

nextFontPositionX += charAdvance + kernings[i] + theLabel->_additionalKerning;


이상입니다.~


참고 : https://github.com/cocos2d/cocos2d-x/search?q=setAdditionalKerning&ref=cmdform




버젼  : cocos2d-x 3.1


cocostudio 를 사용 하여 AnimationEditor 작업 후 파일을 Export 하면 3개의 파일이 생성 되는 것 까지는 생략 하겠습니다.


Size visibleSize = Director::getInstance()->getVisibleSize();


// 파일을 먼저 로딩 //

    cocostudio::ArmatureDataManager::getInstance()->addArmatureFileInfo("test.ExportJson");

     

// 애니메이션 생성 한후 //

    Armature *armature = cocostudio::Armature::create("test");

    armature->setPosition(Vec2(visibleSize.width / 2 , visibleSize.height / 2));

    armature->setScale(5.0f);

// 몇번째 애니메이션을 실행 할것인지 인덱스로 해도 되고 아니면 애니메이션 명으로 실행 해도

//    armature->getAnimation()->play("test");

    armature->getAnimation()->playWithIndex(1);


// 애니메이션 속도 조절 가능 RPG 게임 2배속 기능 참고

    armature->getAnimation()->setSpeedScale(0.1f);

    

    

    //애니메이션 시작 중간 끝났을때 콜백 받을수 있음

    armature->getAnimation()->setMovementEventCallFunc(CC_CALLBACK_0(LobbyScene::animationEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

    

    // 프레임당 이벤트 메서드가 있을시 콜백 받음

    armature->getAnimation()->setFrameEventCallFunc(CC_CALLBACK_0(LobbyScene::onFrameEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));

    

    this->addChild(armature);


======= call back func ======

void ********::onFrameEvent(Bone *bone, const std::string& evt, int originFrameIndex, int currentFrameIndex)

{

    CCLOG("(%s) emit a frame event (%s) at frame index (%d).", bone->getName().c_str(), evt.c_str(), currentFrameIndex);

    

    if((__String::createWithFormat("%s",evt.c_str()))->isEqual(StringMake("fire"))) {

        log("Event Start");

    }

    

    if(strcmp(evt.c_str(),"event")) {

        log("Event Start");

    }

}


void ************::animationEvent(Armature *armature, MovementEventType movementType, const std::string& movementID)

{

    if (movementType == LOOP_COMPLETE)

    {

        if (movementID == "test1")

        {

            log("test complete");

        }

    }

}


이상입니다.~


-------------------------

또한 지금 작업 하고 있는 프로젝트에서 따로 h파일을 하나 생성 하여 cocos2d관련 h파일을 다 포함 하여 작업을 진행 중입니다. 


test.h


#include "cocos2d.h"

#include "cocostudio/CocoStudio.h"


#if(CC_PLATFORM_ANDROID == CC_TARGET_PLATFORM)

#include "extensions/cocos-ext.h"

#elif(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

#include "cocos-ext.h"

#endif


using namespace cocos2d;

using namespace std;

using namespace extension;

using namespace cocostudio;


--------------------------

이 상태에서 각 코코스 및 코코스 스튜디오를 작업 하실때 #include "test.h" 만 추가 하셔서 사용 하시면 됩니다.


예전에는 

this->setTouchEnabled(false)  이였는데 ...


3.0으로 넘어 오면서 


화면의 모든 터치이벤트 멈춤

Director::getInstance()->getEventDispatcher()->setEnabled(false);

하나의 타켓(클래스)의 터치이벤트 멈춤

Director::getInstance()->getEventDispatcher()->pauseEventListenersForTarget(this);

다시시작

Director::getInstance()->getEventDispatcher()->resumeEventListenersForTarget(this);

[출처] touchevent|작성자 웅디베어



참고 하세요.



cocos2d-x 3.x 버젼에서 안드로이드 터미널 빌드시 


make: *** No rule to make target 

make: *** Waiting for unfinished jobs....

Traceback (most recent call last):

  File "./build_native.py", line 166, in <module>

    build(opts.ndk_build_param,opts.android_platform,opts.build_mode)

  File "./build_native.py", line 153, in build

    do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,android_platform,build_mode)

  File "./build_native.py", line 89, in do_build

    raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")


위와 같은 내용의 오류가 나올때가 있습니다.

해결 방법은


proj.android / obj 의 폴더를 모두 지우고 다시 빌드 하면 


정상 작동 합니다.



EGLView::getInstance()->setDesignResolutionSize(width , height, policy)




EXACT_FIT

 - 비율을 고려하지 않고 디자인된 해상도를 화면에 맞추어 그린다.비율에 의한 왜곡이 발생할 수 있다.게임 화면이 늘어 나거나

   압축되어 보일수 있다.


NO_BORDER

 - 비율을 지키며 디자인된 해상도를 화면에 가득차게 그린다.왜곡은 발생하지 않으나 게임 화면의 일부가 단말기 화면 밖으로      잘려 보일 수 있다.


SHOW_ALL

 - 비율을 지키며 디자인된 해상도를 화면에 맞추어 그려준다.디자인된 리소스와 다른 비율의 화면에서는 화면의 양쪽 사이드

   에 검은색의 Border가 등장하게 된다.


FIXED_HEIGHT

  - 디자인된 해상도의 높이에 맞추어 단말기 화면의 비율에 따라 높이를 결정한다. 왜곡은 발생하지 않으나 비율이 고정되지 않     기 때문에 비율에 상관없이 정상적으로 동작하는 것을 개발자가 보장해 주어야 한다.


FIXED_WIDTH

  - 디자인된 해상도의 넓이에 맞추어 단말기 화면의 비율에 따라 넓이를 결정한다. 이하 FIXED_HEIGHT와 동일


MAC에서  cocos2d-x 3.x 세팅 하는 방법을 나열 하겠다.


1. 당연히 xcode는 기본적으로 설치가 되어 있어야 한다.(mac App Store 에서 다운로드 가능)

2. JDK 설치 하기(http://www.oracle.com) 최신 버전으로 설치 하기.(MAC용)

3. ADT Bundle 설치 하기(http://developer.android.com)

    - 다운로드 완료후 원하는 경로에 압축 해제를 하면됨.

    - eclipse 실행시 혹시 보안 경고 팝업창이 발생이 되면 (참고 :http://flyburi.com/573)


4. Android NDK 설치하기(http://developer.android.com/tools/sdk/ndk/)

    - ADT와 마찬가지로 다운로드 완료후 원하는 경로에 압축 해제 하셔서 사용 하면 됨.

   


5. Python 설치하기(www.python.org)


6. cocos2d-X 설치하기(http://www.cocos2d-x.org)


이상~


역시 extable 키 값을 각각 지정 해주시면 됩니다. ^^아래의 값은 임시 적입니다.~


const unsigned char extable[4] = {0x1D, 0x1D, 0x1B, 0xF1};


void IntToByte(int num, unsigned char* value)

{

    value[0] = ((unsigned char)(num >> 24)) ^ extable[0];

    value[1] = ((unsigned char)(num >> 16)) ^ extable[1];

    value[2] = ((unsigned char)(num >> 8)) ^ extable[2];

    value[3] = ((unsigned char)(num)) ^ extable[3];

}


void IntToByteNon(int num, unsigned char* value)

{

    value[0] = ((unsigned char)(num >> 24));

    value[1] = ((unsigned char)(num >> 16));

    value[2] = ((unsigned char)(num >> 8));

    value[3] = ((unsigned char)(num));

}


int ByteToInt(unsigned char* value)

{

    int retV = 0;

    

    retV = (((value[0] & 0xFF) ^ extable[0]) << 24) |

    (((value[1] & 0xFF) ^ extable[1]) << 16) |

    (((value[2] & 0xFF) ^ extable[2]) << 8) |

    ((value[3] & 0xFF) ^ extable[3]);

    

    return retV;

}


int ByteToIntNon(unsigned char* value)

{

    int retV = 0;

    

    retV = (((value[0] & 0xFF)) << 24) |

    (((value[1] & 0xFF)) << 16) |

    (((value[2] & 0xFF)) << 8) |

    ((value[3] & 0xFF));

    

    return retV;

}


- (int) setInt_XOR:(int)value {

    IntToByte(value,_changeBuf);

    return ByteToIntNon(_changeBuf);

}


- (int) getInt_XOR:(int)value {

    memset(_changeBuf, 0x00, 4);

    IntToByteNon(value,_changeBuf);

    return ByteToInt(_changeBuf);

}

http://www.cocos2d-iphone.org/forum/topic/8424
http://www.admob.com
애드몹을 사용 하시기 위해서는 위의 사이트에서 등록 하여 고유 넘버 키를 받으셔야 사용이가능 합니다.
참고 사이트 입니다.


=============================================================================
AdViewController.h
#import <UIKit/UIKit.h>
#import <iAd/iAd.h>
#import "AdMobDelegateProtocol.h"

@protocol AdViewControllerDelegate;

@interface AdViewController : UIViewController <ADBannerViewDelegate, AdMobDelegate>
{
	id <AdViewControllerDelegate> delegate;
	id adBannerView;

	AdMobView* adMobAd;
}

@property (nonatomic, assign) id <AdViewControllerDelegate> delegate;

- (id)initWithMasterView:(UIView*)masterView;
- (void)rotateBannerView:(UIDeviceOrientation)toDeviceOrientation;

@end

@protocol AdViewControllerDelegate

- (void)adController:(AdViewController*)controller didLoadiAd:(id)iadBanner;
- (void)adController:(AdViewController*)controller didFailedToRecieveiAd:(id)iadBanner;

- (void)adController:(AdViewController*)controller didLoadAdMobAd:(AdMobView*)adMobBanner;
- (void)adController:(AdViewController*)controller didFailedToRecieveAdMobAd:(AdMobView*)adMobBanner;

@end

AdViewController.m

#import "AdViewController.h"
#import "cocos2d.h"

#import "AdMobView.h"

@implementation AdViewController

@synthesize delegate;

- (UIDeviceOrientation)currentOrientation
{
	return [[CCDirector sharedDirector] deviceOrientation];
}

- (id) initWithMasterView:(UIView*) masterView
{
	if( nil != (self = [super init]) )
	{
		[self setView:masterView];

		//Initialize the class manually to make it compatible with iOS < 4.0
		Class classAdBannerView = NSClassFromString(@"ADBannerView");
		if (classAdBannerView != nil)
		{
			adBannerView = [[classAdBannerView alloc] initWithFrame:CGRectZero];
			[adBannerView setDelegate:self];
			[adBannerView setRequiredContentSizeIdentifiers: [NSSet setWithObjects:
															  ADBannerContentSizeIdentifier320x50,
															  ADBannerContentSizeIdentifier480x32, nil]];

			[self.view addSubview:adBannerView];

			[self rotateBannerView:[self currentOrientation]];

			[adBannerView setHidden:YES];

		}
		else
		{
			//Request an AdMob Ad
			adMobAd = [AdMobView requestAdOfSize:ADMOB_SIZE_320x48 withDelegate:self];
			[adMobAd retain];
		}
	}

	return self;
}

- (void)rotateBannerView:(UIDeviceOrientation)toDeviceOrientation
{
	if (adBannerView)
	{
		if (UIDeviceOrientationIsLandscape(toDeviceOrientation))
			[adBannerView setCurrentContentSizeIdentifier:ADBannerContentSizeIdentifier480x32];
		else
			[adBannerView setCurrentContentSizeIdentifier:ADBannerContentSizeIdentifier320x50];

		[(UIView*)adBannerView setTransform:CGAffineTransformIdentity];

		//Set the transformation for each orientation
		switch (toDeviceOrientation)
		{
			case UIDeviceOrientationPortrait:
			{
				[(UIView*)adBannerView setCenter:CGPointMake(160, 455)];
			}
				break;
			case UIDeviceOrientationPortraitUpsideDown:
			{
				[(UIView*)adBannerView setTransform:CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(180))];
				[adBannerView setCenter:CGPointMake(160, 25)];
			}
				break;
			case UIDeviceOrientationLandscapeLeft:
			{
				[(UIView*)adBannerView setTransform:CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(90))];
				[adBannerView setCenter:CGPointMake(16, 240)];
			}
				break;
			case UIDeviceOrientationLandscapeRight:
			{
				[(UIView*)adBannerView setTransform:CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(-90))];
				[adBannerView setCenter:CGPointMake(304, 240)];
			}
				break;
			default:
				break;
		}
	}

	if (adMobAd)
	{
		[adMobAd setTransform:CGAffineTransformIdentity];

		//Set the transformation for each orientation
		switch (toDeviceOrientation)
		{
			case UIDeviceOrientationPortrait:
			{
				[adMobAd setCenter:CGPointMake(160, 456)];
			}
				break;
			case UIDeviceOrientationPortraitUpsideDown:
			{
				[adMobAd setTransform:CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(180))];
				[adMobAd setCenter:CGPointMake(160, 24)];
			}
				break;
			case UIDeviceOrientationLandscapeLeft:
			{
				[adMobAd setTransform:CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(90))];
				[adMobAd setCenter:CGPointMake(24, 240)];
			}
				break;
			case UIDeviceOrientationLandscapeRight:
			{
				[adMobAd setTransform:CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(-90))];
				[adMobAd setCenter:CGPointMake(296, 240)];
			}
				break;
			default:
				break;
		}
	}
}

#pragma mark -
#pragma mark ADBannerViewDelegate

- (BOOL)allowActionToRun
{
	return YES;
}

- (void) stopActionsForAd
{
	//Pause background music here

	[adBannerView setHidden:YES];

	[[CCDirector sharedDirector] stopAnimation];
	[[CCDirector sharedDirector] pause];
}

- (void) startActionsForAd
{
	//Resume background music here

	[self rotateBannerView:[self currentOrientation]];
	[[UIApplication sharedApplication] setStatusBarOrientation:(UIInterfaceOrientation)[self currentOrientation]];
	[adBannerView setHidden:NO];

	[[CCDirector sharedDirector] stopAnimation];
	[[CCDirector sharedDirector] resume];
	[[CCDirector sharedDirector] startAnimation];
}

- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{
	BOOL shouldExecuteAction = [self allowActionToRun];
    if (!willLeave && shouldExecuteAction)
    {
		[self stopActionsForAd];
    }
    return shouldExecuteAction;
}

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
	[adBannerView setHidden:NO];
	[delegate adController:self didLoadiAd:banner];
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
	[adBannerView setHidden:YES];
	[delegate adController:self didFailedToRecieveiAd:banner];
}

- (void)bannerViewActionDidFinish:(ADBannerView *)banner
{
	[self startActionsForAd];
}

#pragma mark -
#pragma mark AdMobDelegate methods

- (NSString *)publisherIdForAd:(AdMobView *)adView
{
	return @"your_admob_publisher_id";    //replace it with you publisher id
}

- (UIViewController *)currentViewControllerForAd:(AdMobView *)adView {
	return self;
}

- (UIColor *)adBackgroundColorForAd:(AdMobView *)adView
{
	return [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (UIColor *)primaryTextColorForAd:(AdMobView *)adView
{
	return [UIColor colorWithRed:1 green:1 blue:1 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (UIColor *)secondaryTextColorForAd:(AdMobView *)adView
{
	return [UIColor colorWithRed:1 green:1 blue:1 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (NSArray *)testDevices
{
	return [NSArray arrayWithObjects: ADMOB_SIMULATOR_ID, nil];
}

- (void)didReceiveAd:(AdMobView *)adView
{
	CCLOG(@"AdMob: Did receive ad");

	[self rotateBannerView:[self currentOrientation]];
	[self.view addSubview:adMobAd];

	[delegate adController:self didLoadAdMobAd:adView];
}

// Sent when an ad request failed to load an ad
- (void)didFailToReceiveAd:(AdMobView *)adView
{
	CCLOG(@"AdMob: Did fail to receive ad");
	[adMobAd removeFromSuperview];
	[adMobAd release];
	adMobAd = nil;

	[delegate adController:self didFailedToRecieveAdMobAd:adView];
}

#pragma mark -
#pragma mark Memory Management

- (void) dealloc
{
	if (adMobAd)
	{
		[adMobAd setDelegate:nil];
		[adMobAd removeFromSuperview];
		[adMobAd release];
		adMobAd = nil;
	}

	if (adBannerView)
	{
		[adBannerView setDelegate:nil];
		[adBannerView removeFromSuperview];
		[adBannerView release];
		adBannerView = nil;
	}

    [super dealloc];
}

@end

The usage is very simple, #import AdViewController.h in you Layer's .h and add the delegate protocol AdViewControllerDelegate

#import "AdViewController.h"

@interface Menu : CCLayer <AdViewControllerDelegate>
{
	AdViewController	*adController;
}

And in your layer's .m add this

- (void)onEnter
{
	[super onEnter];

	adController = [[AdViewController alloc] initWithMasterView:[[CCDirector sharedDirector] openGLView]];
	[adController setDelegate:self];

}

- (void)onExit
{
	//Completely remove the controller
	[adController setDelegate:nil];
	[adController release];
	adController = nil;

	[super onExit];
}

- (void)adController:(AdViewController*)controller didLoadiAd:(id)iadBanner;
{
	//Do something when the ad loads, like moving objects.
}

- (void)adController:(AdViewController*)controller didFailedToRecieveiAd:(id)iadBanner;
{
	//Do something when the ad fails to load, like moving objects.;
}

- (void)adController:(AdViewController*)controller didLoadAdMobAd:(AdMobView*)adMobBanner;
{
	//Do something when the ad loads, like moving objects.
}

- (void)adController:(AdViewController*)controller didFailedToRecieveAdMobAd:(AdMobView*)adMobBanner;
{
	//Do something when the ad fails to load, like moving objects.
}
훌 이분 용자인듯 0.0

// Get Documents Directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];


// Create Directory

NSString *tmpDir = [documentsDirectory stringByAppendingPathComponent:@"test_dir"];

mkdir([tmpDir cStringUsingEncoding:NSASCIIStringEncoding], 0777);


// Open File

NSString *tmpFile = [documentsDirectory stringByAppendingPathComponent:@"test_file.txt"];

FILE *file = fopen([tempFile cStringUsingEncoding:NSASCIIStringEncoding], "w");;

//h파일


#import "cocos2d.h"


@interface SpritePosChange : CCScene {

}


-(void) SpritePosChange:(CCSprite*)mSprite : (int) xPos : (int) yPos;


@end




//m파일

#import "SpritePosChange.h"



@implementation SpritePosChange

-(id) init

{

if((self = [super init]))

{

}

return self;

}

-(void) SpritePosChange:(CCSprite*)mSprite : (int) xPos : (int) yPos

{

mSprite.anchorPoint = ccp(0,1);

mSprite.position = ccp(xPos,480-yPos);

}

-(void)dealloc

{

[super dealloc];

}


@end



//아주 간단한 클래스 입니다 ^^ 왕초보라서.~! 그냥 좌상단이 보통 0,0 인데  OpenGl의 기준점은 좌하단이 0,0으로 되어 있어서 
  디자이너들의 좌표 와 정반대로 찍혀 있어서 그냥 만들어 봤음. ^^

//

+ Recent posts