'분류 전체보기'에 해당되는 글 495건

  1. 2014.01.09 [Basic Concepts] Director, Scene, Layer, Sprite 개념 정리
  2. 2014.01.09 [Coordinate System] cocos2d-x 좌표 시스템
  3. 2014.01.09 c++ 11 이란??
  4. 2014.01.09 cocos2d-x v3.0 Beta 출시 되었습니다.
  5. 2014.01.09 [유니티3d][에셋] 유니티 필수 에셋 iTween 에 대해서 알아보자(Action!)
  6. 2014.01.08 [Animations] cocos2d-x 에니메이션 적용하기
  7. 2014.01.08 [디자인패턴] cocos2d-x 싱글톤 싱글턴 패턴 구현
  8. 2014.01.08 [Action] cocos2d-x 액션 사용법
  9. 2014.01.07 strncpy 로 메모리 복사
  10. 2014.01.07 C언어 배열 초기화 방법

[Basic Concepts] Director, Scene, Layer, Sprite 개념 정리

|

Director Scene Layer and Sprite

Scenes

Cocos2d-x에서 씬은 하나의 게임을 그 기능과 성격에 따라 여러 부분으로 나눌 때 사용하는 개념이다. 어떤 개발자들은 씬을 스크린이나 스테이지라고도 부르는데 모두 같은 개념이다. 

씬은 게임의 흐름으로부터 매우 독립적이다. 보통 여러 개의 씬이 모여 하나의 게임을 이루는데 한순간에 하나의 씬만 활성화된다. 각각의 씬은 서로 연결될 수 있기는 하지만 독립된 프로그램으로 생각해도 무방하다.

예들 들어, 만들어진 하나의 게임은 인트로(Intro), 메뉴(Menu), 레벨(Level) 1, 컷씬(Cutscene) 1, 레벨(Level) 2, 승리 결과 화면(Winning cutscene), 패배 결과 화면(Losing cutscene), 랭킹(High score) 등의 씬을 갖게 된다. 

좀더 자세히 설명하면, 게임이 시작되고 인트로 씬이 끝나면 메뉴 씬으로 이동한다. 다음으로 레벨 1 씬으로 전환된 뒤 컷씬이 종료되면, 사용자의 승패 여부에 따라 승리 또는 패배 결과 화면으로 씬이 전환된다. 

cocos2d CCScene 은 하나이상의 CCNode로 구성되며 Scene의 자식으로 더해집니다.

CCLayer 및 CCSprite(CCNode를 상속받는)는 모양과 동작을 Scene에 더해준다. 

일반적으로, CCLayer와 CCScene의 빈 인스턴스로 너의 Scene은 구성됩니다.

CCNodes로 다른 그래픽과 게임 객체를 구현하고 사용자가 만든 CCLayer에 자식으로 추가합니다.

Scene는 CCNode의 하위 클래스이므로, 이들은 수동 또는 CCActions을 사용하여 변환 될 수있다. 자세한 내용은 작업을 참조하십시오.

CCTransitionScene 클래스로 구현 전환이라고 CCScene 클래스의 가족이 있습니다. 그래서, 예를 들어 퇴색 측면에서의 슬라이딩, 그리고 - 다른 하나의 장면에서 전환 할 때 이러한 특수 전환 효과를 만들 수 있습니다.


Director

CCDirector는 싱글톤 패턴이며 활성화된 Scene를 알고있으며 현재 Scene를 교체할수있으며, 스택방식으로 push 및 pop으로 Scene를 관리할수있습니다.
그럴 경우 CCDirector은 이전 Scene를 일시중지하지만 메모리에 유지시킵니다. 만약 나중에 너가 맨위 Scene를 pop하면 일시중지된 Scene로 다시 시작합니다.

CCDirector는 OpenGL을 ES를 초기화 할 책임이 있습니다.


Layers

CCLayer가 터치 이벤트를 처리할수있는 CCNode입니다. CCLayer 자체를 그리는 방법을 아는 플레이어가 그들 뒤에 다른 레이어를 볼 수 있도록 반투명 수 있습니다. CCLayers은 게임의 모양과 동작을 정의하는 데 매우 유용합니다, 그래서 당신은 당신이 필요로 할 CCLayer의 서브 클래스를 코딩 프로그래밍 많은 시간을 소비 할 것으로 예상해야한다.

TCCLayer는 터치 이벤트 핸들러를 정의하는 곳이다.터치 이벤트 (ccTouchBegan, ccTouchMoved, ccTouchEnded 또는 ccTouchCancelled) 중 하나를 처리하는 방법을 구현함으로써 CCLayer는 플레이어의 상호 작용에 반응 할 수있다. 일부 Layer은 이벤트를 포착하고 그것을 받아 들일 때까지 이러한 터치 이벤트는, 앞에서 뒤로, 장면 내의 모든 계층에 전파됩니다.

복잡한 응용 프로그램을 사용자 정의 CCLayer 서브 클래스를 정의 할 필요가 동안,적인 Cocos2D는 미리 정의 된 여러 레이어를 제공합니다. 몇 가지 예는 CCMenu (간단한 메뉴 Layer), CCColorLayer (색깔을 그릴수 있는 Layer), 그리고 CCLayerMultiplex (CCLayer를 하나만 쓰고 싶을때) 등이 있습니다.

레이어 CCSprites, CCLabels, 심지어 다른 CCLayer 개체를 포함하여, 아이로 어떤 CCNode를 포함 할 수 있습니다. 층 CCNode의 하위 클래스이므로, 이들은 수동 또는 CCActions을 사용하여 변환 될 수있다. 자세한 내용은 작업을 참조하십시오.

Multiple Layers Example:

 1    CCLayerGradient* layer1 = CCLayerGradient::create(ccc4(255, 0, 0, 255), ccc4(255, 0, 255, 255));
 2    layer1->setContentSize(CCSizeMake(80, 80));
 3    layer1->setPosition(ccp(50,50));
 4    addChild(layer1);
 5
 6    CCLayerGradient* layer2 = CCLayerGradient::create(ccc4(0, 0, 0, 127), ccc4(255, 255, 255, 127));
 7    layer2->setContentSize(CCSizeMake(80, 80));
 8    layer2->setPosition(ccp(100,90));
 9    addChild(layer2);
10
11    CCLayerGradient* layer3 = CCLayerGradient::create();
12    layer3->setContentSize(CCSizeMake(80, 80));
13    layer3->setPosition(ccp(150,140));
14    layer3->setStartColor(ccc3(255, 0, 0));
15    layer3->setEndColor(ccc3(255, 0, 255));
16    layer3->setStartOpacity(255);
17    layer3->setEndOpacity(255);
18    ccBlendFunc blend;
19    blend.src = GL_SRC_ALPHA;
20    blend.dst = GL_ONE_MINUS_SRC_ALPHA;
21    layer3->setBlendFunc(blend);
22    addChild(layer3);

Sprites

Cocos2D의 CCSprite는 다른 게임 엔진에서 찾을 스프라이트 유사합니다. 그것은, 회전, 이동 조정, 애니메이션 및 기타 변환을받을 수있는 2D 이미지입니다. (CCSprite 클래스를 사용하여 구현) 스프라이트는 어린이와 같은 다른 스프라이트를 할 수 있습니다. 부모가 변형 될 때, 모든 아이들은 물론 변환됩니다. 스프라이트 CCNode의 하위 클래스이므로, 이들은 수동 또는 CCActions을 사용하여 변환 될 수있다. 자세한 내용은 작업을 참조하십시오.

Trackback 0 And Comment 0

[Coordinate System] cocos2d-x 좌표 시스템

|

좌표 시스템

기존과 다른 좌표 시스템을 도입.Introduction of Different Coordinate Systems


직교 좌표 시스템(데카르트 좌표)

너는 아마 기하학 수업에 사용되는 좌표를 알고 있을 것이다.

모바일에서는 보통 3가지 정도의 좌표 시스템이 있다.

UI 좌표 시스템

안드로이드나 아이폰에서의 좌표 시스템

  • 좌측 상단이 (0,0) 이다.
  • X 축은 왼쪽에서부터 오른쪽으로 갈수록 증가한다.
  • Y 축은 화면 상단에서 부터 아래로 내려 갈수록 증가한다.

looks like this

Direct3D 좌표 시스템

DirectX 에서는 왼손좌표계를 사용한다.


OpenGL 그리고 Cocos2d 의 좌표시스템

openGL과 cocos2d는 오른손 좌표계를 사용한다.


우리는 2d게임에서 오직 x,y축만 사용합니다. 

  • 좌측 하단이 (0,0) 좌표이고 오른손 좌표계를 사용합니다.
  • X 축은 왼쪽에서부터 오른쪽으로 갈수록 증가합니다.;
  • Y 축은 아래부터 시작하며 위로 갈수록 증가합니다.

좌표 시스템을 좀더 이해하기 쉽도록 아래 사진이 준비되어있음

다이렉트x나 일반적 ui시스템과 다른 좌표시스템이다.


Parent and Childrens

CCNode를 상속받는 모든 클래스는 anchorPoint 속성을 가지고 있습니다.

CCNode를 상속받는 객체를 그릴때(sprite, layer, 기타등등) , cocos2d-x는 anchorpoint와 position를 결합합니다. 또한 물체를 회전할때 Anchorpoint를 기준으로 회전하게됩니다.

우리는 회색배경의 부모 클래스를 만들었고 파란색 배경의 자식클래스를 만들었습니다. 부모의 좌표는((100,100)이고 자식의  anchor point는 중앙입니다.

 1    CCSprite* parent = CCSprite::create("parent.png");
 2    parent->setAnchorPoint(ccp(0, 0));// Anchor Point
 3    parent->setPosition(ccp(100, 100));
 4    parent->setAnchorPoint(ccp(0, 0));
 5    addChild(parent);
 6
 7    //create child 
 8    CCSprite* child = CCSprite::create("child.png");
 9    child->setAnchorPoint(ccp(0.5, 0.5));
10    child->setPosition(ccp(0, 0));
11    parent->addChild(child);//add child sprite into parent sprite.


자식의 위치가 (0,0) 이고 부모의 위치가 (100,100)일때 아래 그림과 같다.

Anchor Point

앵커 포인트의 위치와 개체를 회전 모두에 사용됩니다.앵커 포인트의 좌표는 일반적으로 개체 내 지점에 해당하는 상대 좌표입니다. 예를 들어, 앵커 포인트 CCP (0.5, 0.5)는 객체의 중심에 대응한다.물체의 위치를 설정할 때, 객체는 앵커 포인트로 setPosition () 호출에 지정된 좌표에있을 것이다되도록 위치된다.객체를 회전시킬 때 마찬가지로, 그 기준점에 대해 회전된다.

예를 들어 sprite가 앵커포인트 와 위치가 0,0일때

그 결과 sprite는 하단 왼쪽 모서리에 배치됩니다.

1// create sprite
2CCSprite* sprite = CCSprite::create("bottomleft.png");
3sprite->setAnchorPoint(ccp(0, 0));// Anchor Point
4sprite->setPosition(ccp(0,0));
5addChild(sprite);


예를 들어 sprite가 앵커포인트는 (0.5,0.5) 이고 위치가 0,0일때

1// create sprite
2CCSprite* sprite = CCSprite::create("center.png");
3sprite->setAnchorPoint(ccp(0.5, 0.5));// Anchor Point
4sprite->setPosition(ccp(0,0));
5addChild(sprite);


위와 같이 sprite의 중심이 좌표 0,0에 위치합니다. 앵커포인트는 화소값이 아닌 노드에 상대적인 크기입니다. 0~1 까지 존재함.

getVisibleSize, getVisibleOrigin vs getWinSize

VisibleSize 은 OpenGL상에서 보여지는 크기를 리턴합니다.이 값은  CCEGLView::setDesignResolutionSize()이 함수를 호출하지 않으면 getWinSize와 같습니다.

getVisibleOrigin은 OpenGL상에서 보이는 x,y의 좌표를 반환합니다.


How to convert co-ordinates

convertToNodeSpace:

convertToNodeSpace will be used in, 예를 들어 타일 기반 게임에서, 너가 큰 맵을 가지고 있을때. convertToNodeSpace는 너의 OpenGL 터치 좌표를 큰맵에 있는 좌표계를 기준으로 변형해줍니다.

Example:

다음그림은 보여줍니다. node1의 앵커포인트(0,0)이고 node2의 앵커포인트(1,1)입니다.

우리가  호출하면CCPoint point = node1->convertToNodeSpace(node2->getPosition()); convert node2의 스크린 좌표계는 node1의 좌표계를 기준으로 구해지게 되며 그 결과 node2 의 좌표는 (-25,-60) 이 됩니다.

convertToWorldSpace:

convertToWorldSpace(const CCPoint& nodePoint) coordinates.convertToWorldSpace 항상 우리의 스프라이트의 화면 위치를 반환합니다 당신은 당신의 스프라이트에 탭을 캡처 할하지만 레이어를 확장 / 이동해야하는 경우 매우 유용 할 수 있습니다 화면에 노드 좌표입니다 변환합니다.


일반적으로, 자식 노드의 위치와 부모 노드 호출이 방법은 결과로 아이의 세계의받은 위치를 반환합니다. 호출자가 부모가 아닌 경우이 메서드를 호출 아무 의미도하지 않습니다 것 같다 ...

Example:

1CCPoint point = node1->convertToWorldSpace(node2->getPosition()); 

위의 코드는 화면의 좌표로 노드 2의 좌표를 변환합니다.

예를 들어, 노드 1의 앵커 위치 (0, 0)이 화면에 필요없는 노드 1의 왼쪽 하단 모서리, 그러나되는 경우. 이 화면에 점의 (-5, -20) 좌표 노드 1에 대해 (이 경우)가 (15, 20입니다) (-20, -5)는 노드 2의 위치를 ​​변환합니다.결과는 다음 그림에서 보여줍니다

convertToWorldSpaceAR,

convertToWorldSpaceAR 지점을 고정하는 relatevely 위치를 반환합니다, 그래서 우리의 장면 경우 - 루트 층은 CCP의 앵커 포인트 (0.5F, 0.5F)이 - 기본, convertToWorldSpaceAR은 상대적으로 화면 중앙에 위치를 반환해야합니다.

convertToNodeSpaceAR -. convertToWorldSpaceAR와 동일한 논리

Sample code:

 1
 2CCSprite *sprite1 = CCSprite::create("CloseNormal.png");
 3
 4sprite1->setPosition(ccp(20,40));
 5
 6sprite1->setAnchorPoint(ccp(0,0));
 7
 8this->addChild(sprite1);
 9
10CCSprite *sprite2 = CCSprite::create("CloseNormal.png");
11
12sprite2->setPosition(ccp(-5,-20));
13
14sprite2->setAnchorPoint(ccp(1,1));
15
16this->addChild(sprite2);
17
18CCPoint point1 = sprite1->convertToNodeSpace(sprite2->getPosition());
19
20CCPoint point2 = sprite1->convertToWorldSpace(sprite2->getPosition());
21
22CCPoint point3 = sprite1->convertToNodeSpaceAR(sprite2->getPosition());
23
24CCPoint point4 = sprite1->convertToWorldSpaceAR(sprite2->getPosition());
25
26CCLog("position = (%f,%f)",point1.x,point1.y);
27
28CCLog("position = (%f,%f)",point2.x,point2.y);
29
30CCLog("position = (%f,%f)",point3.x,point3.y);
31
32CCLog("position = (%f,%f)",point4.x,point4.y);
33

Result:

 1
 2position = (-25.000000,-60.000000)
 3
 4position = (15.000000,20.000000)
 5
 6position = (-25.000000,-60.000000)
 7
 8position = (15.000000,20.000000)
 9



Trackback 0 And Comment 0

c++ 11 이란??

|

C++11

위키백과, 우리 모두의 백과사전.

C++ 11(C++0x라고도 알려짐)은 [1] ISO가 2011년 8월 12일에 승인한 C++ 프로그래밍 언어의 최신판이다. [2] 이름은 사양이 출판되는 날짜를 언어 버전 이름으로 삼는 전통에서 유래되었다.

C++11은 핵심 언어에 여러가지를 추가하고 C++ 표준 라이브러리를 확장하고, C++ 기술 보고서 1(TR1)의 라이브러리의 수학적 특수 함수의 라이브러리 예외를 통합했다.[3] C++11은 ISO/IEC 14882:2011라고 출판되었다.

이전 표준에서의 변화[편집]

C++ 의 수정은 핵심 언어와 표준 라이브러리 모두를 포함한다. 2011 표준안의 모든 활용에 대한 개발에서, 표준 위원회에서는 몇 가지 지침을 적용했다.

  • 안정성 및 C++98(가능하면 C언어와도)과의 호환성 유지
  • 핵심 언어의 확장보다는 표준 라이브러리를 이용하려 새로운 기능 추가
  • 프로그래밍 기술을 발전시킬 변화 선호
  • 특정 애플리케이션에서만 유용한 새로운 기술보다는 시스템이나 라이브러리 디자인에 유용하게 C++을 개선
  • 이전의 안전하지 않은 기술에 대해 좀 더 안전한 대안을 제공하여 type 안전성 증가
  • 성능 향상과 하드웨어 직접 조작 능력 강화
  • 실 세계의 문제를 해결할 수 있는 해법 제시
  • "부담 최소화"의 원칙 (어떤 유틸리티가 필요로 하는 추가적인 지원은 그 유틸리티를 사용할 때만 필요해야 함)
  • 전문 프로그래머가 필요로 하는 어떤 유틸리티도 제거하지 않고도, 쉽게 가르치거나 배울 수 있어야 함

프로그래머 중 초심자가 대다수이며, 많은 초심자들은 C++에 대한 지식을 늘리기 보다는 그들에게 특화된 언어 측면에만 매진하는 경향이 있기 때문에 그들에 대해 주의를 기울이는 것이 중요하다.

C++ 언어의 문법 확장[편집]

C++ 위원회의 주된 관심은 언어 문법을 개발하는 것이다. C++0x의 프리젠테이션 일정은 표준안에서 이 부분의 진행에 영향을 받는다.

언어의 문법적 범위는 멀티태스킹 지원, 제네릭 프로그래밍 지원, 초기화 방법 통합, 성능 향상 등으로 매우 증가하였다.

이 문서의 목적에 맞게, 문법적 기능과 변화는 "런타임 성능 향상", "컴파일 성능 향상", "편의성 향상", "새로운 기능"등의 4부분으로 그룹화하였다. 일부 기능은 여러 부분에서 언급될 수 있지만, 주된 기능에 대해서 한번씩만 설명할 것이다.

핵심 언어 - 런타임 성능 향상[편집]

아래 나열된 기능은 주로 메모리나 계산 속도에 대한 성능 향상을 제공한다.

문법 기능의 편의성 향상[편집]

문법의 새로운 기능[편집]

  • 템플릿에서의 가변 인자
  • 새로운 문자열 리터럴
  • 사용자 정의 리터럴
  • 멀티태스킹 메모리 모델
  • TLS
  • 특수 멤버함수에 대해 기본값 사용및 삭제에 대한 명시적 표시
  • long long int 자료형
  • 정적 assertion
  • 멤버에 대한 sizeof 허용

C++ 표준 라이브러리의 변화[편집]

새로운 기능의 상당수는 C++0x 표준 라이브러리에서 소개된다. 이들중 상당수는 현재의 표준안에서도 구현될 수 있다. 하지만 일부는 C++0x의 새로운 문법에 의존한다.

새로운 라이브러리의 대부분은 C++ 표준 위원회의 TR1이라고 불리는 기술 보고서에서 정의되고 있으며 이는 2005년에 발표되었다. TR1의 대부분은 std::tr1 네임스페이스에서 현재 이용가능하다. C++0x에 맞게 그 네임스페이스를 std로 이동할 것이다. 하지만 C++0x 표준 라이브러리에서 TR1 기능이 제공됨에 따라, 초기 TR1에서 제공되지 않았던 기능들과 함께 적당한 위치로 업그레이드될 것이다. 또한 C++03에서 구현 가능했던 기능들을 C++0x에 맞게 향상되겠지만 오리지날 TR1 규정의 부분은 아니다.

위원회는 C++0x 표준안이 완료된 이후에 TR2를 계획하고 있다. C++0x를 만들면서 준비되지 못한 라이브러리 제안사항은 TR2나 그 뒤의 기술 보고서에서 다룰 것이다.

다음 제안 사항들은 C++0x에서 진행되고 있다.

  • 표준 라이브러리의 업그레이드
  • 스레드
  • 튜플 자료형
  • 해시 테이블
  • 정규 표현식
  • 범용 스마트 포인터
  • 확장가능한 난수 생성기
  • wrapper 레퍼런스
  • 함수객체에 대한 다형성이 있는 wrapper
  • 메타 프로그래밍을 위한 type traits
  • 함수객체의 리턴형에 대한 방법

적용[편집]

C++11은 GCC 4.3부터[4] 4.7에서[5] 시험적용되고 있고, Visual Studio 10[6]부터 Visual Studio 12[7]까지 부분적으로 적용되고 있다.

인용[편집]

  1. 이동 http://video.google.com/videoplay?docid=5262479012306588324#
  2. 이동 We have an international standard: C++0x is unanimously approved. 12 August 2011에 확인.
  3. 이동 Bjarne Stroustrup: A C++0x overview. 30 June 2011에 확인.
  4. 이동 http://gcc.gnu.org/projects/cxx0x.html
  5. 이동 http://gcc.gnu.org/gcc-4.7/cxx0x_status.html
  6. 이동 http://blogs.msdn.com/b/vcblog/archive/2010/04/06/c-0x-core-language-features-in-vc10-the-table.aspx
  7. 이동 http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx

바깥 고리[편집]






'잡다한것들전부 > C, C++, C#' 카테고리의 다른 글

추상 클래스 (C++)  (0) 2014.01.10
Duff's Device  (0) 2014.01.10
c++ 11 이란??  (0) 2014.01.09
strncpy 로 메모리 복사  (0) 2014.01.07
C언어 배열 초기화 방법  (0) 2014.01.07
c++ stl 관련 자료  (0) 2014.01.06
Trackback 0 And Comment 0

cocos2d-x v3.0 Beta 출시 되었습니다.

|

cocos2d-x v3.0 Beta


Highlights

  • New renderer. Renderer has being decoupled from the Scene Graph. It supports auto-batching and auto-culling.
  • Added template containers. cocos2d::Map<>cocos2d::Vector<>
  • Label supports: shadow, glow and outline (beta)
  • Added Joint support in the physics subsystem
  • Added Console: A simple TCP console that lets you debug and inspect your game remotely
  • tools/project_creator/project_creator.py includes a GUI to simplify the game creation process. It also allows you to create the game in any given directory.
  • Added support to build Android's APK files in the android-build.py script
  • Added Scheduler::performFunctionInCocosThread(). It supports executing a function in the cocos2d thread
  • Director emits the following events using the EventDispatcherAFTER_UPDATEAFTER_DRAW,AFTER_VISIT and PROJECTION_CHANGED
  • Added Cocos2dxActivity.java which inherits from native activity. Ingetrating 3rd Android SDK would be much easilier on v3.0.

Read more about all the new features at cocos2d-x v3.0 release notes


알파에서 베타버전으로 출시되이써습니다.

정식버전이 기대됩니다.

'잡다한것들전부 > 소식' 카테고리의 다른 글

cocos2d-x v3.0 Beta 출시 되었습니다.  (0) 2014.01.09
Trackback 0 And Comment 0

[유니티3d][에셋] 유니티 필수 에셋 iTween 에 대해서 알아보자(Action!)

|


유니티 필수 에셋 중에 하나인 아이트윈

유니티에서 물체의 움직임을 보다 쉽게 설정 할 수 있습니다.

유니티를 켜시고 에셋 스토어로 갑시다 ctrl + 9 를 누르면 Asset Store에 들어가집니다.
iTween 으로 검색하시면 아래와 같이 화면이 나오고 다운로드 버튼을 누르고 유니티 상에 import 시켜줍니다. 





파일을 여시면 sample 소스가 존재합니다. sample 소스를 보시면 iTween 이라는게 뭐구나 하고 싶게 이해 할수있으실겁니다.




간단하게 샘플 소스에 대해 알아보겠습니다.




using UnityEngine;

using System.Collections;

 

public class MoveSample : MonoBehaviour

{               

                  void Start(){

                                   iTween.MoveBy(gameObject, iTween.Hash("x", 2, "easeType", "easeInOutExpo", "loopType", "pingPong", "delay", .1));

                  }

}


moveSample 입니다.


  • MoveBy(GameObject target, Vector3 amount, float time)
  • MoveBy(GameObject target, Hashtable args)

  • moveBy를 호출하는 방법은 위와 같이 두가지 방법이 있습니다.

    첫번째는 호출 방법은 위치와 시간을 집어넣어주는 함수이고

    두번째는 호출 방법은 해쉬테이블을 집어넣는 방식입니다.


    위함수에서는

    x = 2;

    easeType = "easeInOutExpo"

    loopType = "pingPong"

    delay = .1;

    해쉬테이블의 name 에 각 값들을 집어넣은 것과 같습니다.

    해쉬테이블을 미리 선언하고 아래와 같이 집어넣을 수 도 있습니다.


    Hashtable ht = new Hashtable();
    	
    void Awake(){
    	ht.Add("x",3);
    	ht.Add("time",4);
    	ht.Add("delay",1);
    	ht.Add("onupdate","myUpdateFunction");
    	ht.Add("looptype",iTween.LoopType.pingPong);
    }
    
    void Start(){
    	iTween.MoveTo(gameObject,ht);
    }



    함수의 종류는 아래와 같습니다.


    MoveBy BACK TO TOP

    Adds the supplied coordinates to a GameObject's position.

    • MoveBy(GameObject target, Vector3 amount, float time)
    • MoveBy(GameObject target, Hashtable args)
    Property NameTypePurpose
    namestringan individual name useful for stopping iTweens by name
    amountVector3for a point in space the GameObject will animate to.
    xfloat or doublefor the individual setting of the x axis
    yfloat or doublefor the individual setting of the y axis
    zfloat or doublefor the individual setting of the z axis
    orienttopathbooleanfor whether or not the GameObject will orient to its direction of travel. False by default
    looktargetTransform or Vector3for a target the GameObject will look at
    looktimefloat or doublefor the time in seconds the object will take to look at either the "looktarget" or "orienttopath"
    axisstringrestricts rotation to the supplied axis only
    spaceSpacefor applying the transformation in either the world coordinate or local cordinate system. Defaults to local space
    timefloat or doublefor the time in seconds the animation will take to complete
    speedfloat or doublecan be used instead of time to allow animation based on speed
    delayfloat or doublefor the time in seconds the animation will wait before beginning
    easetypeEaseType or stringfor the shape of the easing curve applied to the animation
    looptypeLoopType or stringfor the type of loop to apply once the animation has completed
    onstartstringfor the name of a function to launch at the beginning of the animation
    onstarttargetGameObjectfor a reference to the GameObject that holds the "onstart" method
    onstartparamsObjectfor arguments to be sent to the "onstart" method
    onupdatestringfor the name of a function to launch on every step of the animation
    onupdatetargetGameObjectfor a reference to the GameObject that holds the "onupdate" method
    onupdateparamsObjectfor arguments to be sent to the "onupdate" method
    oncompletestringfor the name of a function to launch at the end of the animation
    oncompletetargetGameObjectfor a reference to the GameObject that holds the "oncomplete" method
    oncompleteparamsObjectfor arguments to be sent to the "oncomplete" method
    ignoretimescalebooleansetting this to true will allow the animation to continue independent of the current time which is helpful for animating menus after a game has been paused by setting Time.timeScale=0




     

    using UnityEngine;

    using System.Collections;

     

    public class RotateSample : MonoBehaviour

    {               

                      void Start(){

                                       iTween.RotateBy(gameObject, iTween.Hash("x", .25, "easeType", "easeInOutBack", "loopType", "pingPong", "delay", .4));

                      }

    }

     

     

    RotateSample 입니다.


    RotateBy BACK TO TOP

    Multiplies supplied values by 360 and rotates a GameObject by calculated amount over time.

    • RotateBy(GameObject target, Vector3 amount, float time)
    • RotateBy(GameObject target, Hashtable args)

    Property NameTypePurpose
    namestringan individual name useful for stopping iTweens by name
    amountVector3for the amount to be multiplied by 360 to rotate the GameObject.
    xfloat or doublefor the individual setting of the x axis
    yfloat or doublefor the individual setting of the y axis
    zfloat or doublefor the individual setting of the z axis
    spaceSpace or stringfor applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
    timefloat or doublefor the time in seconds the animation will take to complete
    speedfloat or doublecan be used instead of time to allow animation based on speed
    delayfloat or doublefor the time in seconds the animation will wait before beginning
    easetypeEaseType or stringfor the shape of the easing curve applied to the animation
    looptypeLoopType or stringfor the type of loop to apply once the animation has completed
    onstartstringfor the name of a function to launch at the beginning of the animation
    onstarttargetGameObjectfor a reference to the GameObject that holds the "onstart" method
    onstartparamsObjectfor arguments to be sent to the "onstart" method
    onupdatestringfor the name of a function to launch on every step of the animation
    onupdatetargetGameObjectfor a reference to the GameObject that holds the "onupdate" method
    onupdateparamsObjectfor arguments to be sent to the "onupdate" method
    oncompletestringfor the name of a function to launch at the end of the animation
    oncompletetargetGameObjectfor a reference to the GameObject that holds the "oncomplete" method
    oncompleteparamsObjectfor arguments to be sent to the "oncomplete" method
    ignoretimescalebooleansetting this to true will allow the animation to continue independent of the current time which is helpful for animating menus after a game has been paused by setting Time.timeScale=0











    보다 많은 정보는 iTwwen 홈페이지에서 찾아볼수있습니다.

    ITwen 홈페이지 :http://itween.pixelplacement.com/index.php


    관련 동영상 강좌 입니다.


    https://www.youtube.com/watch?v=qRafXt26a_E

    https://www.youtube.com/watch?v=qE5hpp4YaH4


    https://www.youtube.com/watch?v=hbSxwoWjBgQ -> 한글





    Trackback 0 And Comment 0

    [Animations] cocos2d-x 에니메이션 적용하기

    |

    Animations

    Frame Animation

    아래와 같이 여러개의 이미지 파일로 애니메이션을 만들 수 있다.

     1CCAnimation *animation = CCAnimation::create();
     2
     3// load image file from local file system to CCSpriteFrame, then add into CCAnimation
     4for (int i = 1; i < 15; i++)
     5{
     6    char szImageFileName[128] = {0};
     7    sprintf(szImageFileName, "Images/grossini_dance_%02d.png", i);
     8    animation->addSpriteFrameWithFileName(szImageFileName);  
     9}
    10
    11animation->setDelayPerUnit(2.8f / 14.0f); // 14개의 이미지를 2.8초 동안 보여줄때 각 프레임 간격.
    12animation->setRestoreOriginalFrame(true); // 14개의 이미지를 돌린다음에 다시 1프레임으로 돌아간다
    13
    14CCAnimate *action = CCAnimate::create(animation);
    15sprite->runAction(action);  // run action on sprite object
    

    Note that CCAnimation is composed by sprite frames, delay time per frame, durations etc, it's a pack of "data". While CCAnimate is an action, it is created base on CCAnimation object.


    Sprite Sheet Animation

    위 에니메이션 방식은 이해하기 쉽지만, 실제 게임에서는 잘 사용되지 않습니다, 대신 스프라이트 시트 에니메이션을 일반적으로 사용합니다.

    다음은 일반적인 스프라이트 시트입니다. 그것은 애니메이션 스프라이트 프레임 시퀀스이거나 같은 장면에서 사용될 이미지 팩이 될 수있다.


    Creating from .png and .plist file

    CCSpriteSheet 는 1.x  버전이나 그 이하 버전에서 사용되었지만. 2.x 이상 버전에서는 CCSpriteBatchNode 를 사용한다.
    CCSpriteBatchNode는 사실상 스프라이트 프레임 이미지 텍스쳐 이다.  너는 반드시 Scene에 이것을 add해야됩니다. 이것은 add를 해도 실제로는 그려지지 않지만
    렌더링 파이프 라인의 일부가 됩니다.
    예를들면:
    1CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("animations/grossini.png");
    

    그다음에 너는 CCSpriteFrameCache 싱글톤 클래스를 사용하여 plist 파일을 로드합니다.

    1CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    2cache->addSpriteFramesWithFile("animations/grossini.plist"); 

    CCSpriteBatchNode와 프레임이로드 및 스프라이트 시트를 장면에 추가되면, 당신은 "createWithSpriteFrameName"방법을 사용하고, CCSpriteBatchNode  자식으로 추가하여 이러한 프레임을 사용 스프라이트를 만들 수 있습니다 :

    1m_pSprite1 = CCSprite::createWithSpriteFrameName("grossini_dance_01.png");
    2spritebatch->addChild(m_pSprite1);
    3addChild(spritebatch);
    

    createWithSpriteFrameName

     이 메서드는  posit 파일을 이용하여 해당되는 사각형 영역을 찾을수 있습니다.

    CCArray 오브젝트에 에니메이션 프레임을 더합니다. 에니메이션 사이즈는 14 프레임이고 우리는 이것을 사용하면 됩니다.

     1CCArray* animFrames = CCArray::createWithCapacity(15);
     2
     3char str[100] = {0};
     4
     5for(int i = 1; i < 15; i++) 
     6{
     7    sprintf(str, "grossini_dance_%02d.png", i);
     8    CCSpriteFrame* frame = cache->spriteFrameByName( str );
     9    animFrames->addObject(frame);
    10}
    

    마지막으로 우리는 CCAnimate 만들고 CCSprite에 runAction을 해줍니다. CCRepeatForever를 이용해서 무한으로 에니메이션을 돌릴수 있습니다.

    1CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, 0.3f);
    2m_pSprite1->runAction( CCRepeatForever::create( CCAnimate::create(animation) ) );
    


    File animation

    CCAnimationCache can load a xml/plist file which well describes the batch node, sprite frame names and their rectangles. The interfaces are much easier to use.

    1CCAnimationCache *cache = CCAnimationCache::sharedAnimationCache(); // "caches" are always singletons in cocos2d
    2cache->addAnimationsWithFile("animations/animations-2.plist");
    3CCAnimation animation = cache->animationByName("dance_1");  // I apologize for this method name, it should be getAnimationByName(..) in future versions
    4CCAnimate animate = CCAnimate::create(animation);  // Don't confused between CCAnimation and CCAnimate :)
    5sprite->runAction(animate);
    


    Trackback 0 And Comment 0

    [디자인패턴] cocos2d-x 싱글톤 싱글턴 패턴 구현

    |


    #ifndef __SINGLETON_H__

    #define __SINGLETON_H__

     

    #include "cocos2d.h"

     

    class SingletonClass{

    private:

                      static SingletonClass * instance ;

                      ~SingletonClass(){/*empty*/};

                      SingletonClass(){

                                       value = 10;};

    public:

                      static SingletonClass * getInstance();

                      static void releaseInstance();

     

                      int value;

                     

    };

    #endif

     

     

    #include "Singleton.h"

     

    SingletonClass * SingletonClass::instance = NULL ;

     

    SingletonClass * SingletonClass::getInstance()

    {

                      if (!instance)

                      {

                                       instance = new SingletonClass();

                      }

     

                     return instance;

    }

     

    void SingletonClass::releaseInstance()

    {

                      if(instance) delete instance;

    }

     



    사용법

    #include "Singleton.h"

    CCLOG("VALUE %d", SingletonClass::getInstance()->value);

    이런식으로 접근가능


    Trackback 0 And Comment 0

    [Action] cocos2d-x 액션 사용법

    |


    Actions



    Actions 클래스는 CCNode 를 상속받는 모든 객체에 명령을 부여합니다. 액션은  오브젝트의 위치, 회전, 크기 기타등등 값들을 수정합니다

    일정기간동안 수정하는 작업이면 -> CCIntervalAction actions 그렇지 않으면 -> CCInstantAction 입니다.

     예를들면 CCMoveBy는 일정기간동안 수정합니다. CCIntervalAction 액션입니다.

    액션의 사용 예:

    1// 스프라이트가 오른족으로  50 픽셀, 밑으로 10 픽셀 움직임 2초동안.
    2CCActionInterval*  actionBy = CCMoveBy::create(2, ccp(50,10));
    


    가속 관련된 액션들 (점점 빨라지거나 느려지는등)

    • CCEaseIn
    • CCEaseOut
    • CCEaseInOut
    • CCSpeed
      Etc. (See the ActionsEaseTest.cpp example for more info)

    CCActionManager를 사용하면 중간에 액션을 일시정지 하고 재시작 할수도있다.(해당객체의)

    1// Pause actions
    2CCDirector *director = CCDirector::sharedDirector();
    3m_pPausedTargets = director->getActionManager()->pauseAllRunningActions();
    4// resume actions
    5CCDirector *director = CCDirector::sharedDirector();
    6director->getActionManager()->resumeTargets(m_pPausedTargets);
    

    Basic Actions

    Basic actions are the ones that modify basic properties like:

    Position(위치수정관련)

    CCMoveBy
    CCMoveTo
    CCJumpBy
    CCJumpTo
    CCBezierBy
    CCBezierTo
    CCPlace

    Scale(크기수정관련)

    CCScaleBy
    CCScaleTo

    Rotation(회전)

    CCRotateBy
    CCRotateTo

    Visibility(보이는거)

    CCShow
    CCHide
    CCBlink
    CCToggleVisibility

    Opacity(알파값)

    CCFadeIn
    CCFadeOut
    CCFadeTo

    Color(색깔)

    CCTintBy
    CCTintTo

    Example:

    1CCSprite *sprite = CCSprite::create("Images/grossini.png");
    2sprite->setPosition(ccp(100, 100));
    3addChild(sprite);
    4
    5CCMoveBy* act1 = CCMoveBy::create(0.5, ccp(100, 0));
    6sprite->runAction(CCRepeat::create(act1, 1));
    

    The act1 will be a CCMoveBy action of duration 0.5, but with the position value of ccp(100,0).


     뒤에 By 붙는거와 To 붙는거 차이


    By는 현재 값 기준으로 변경 To는 그냥 그런거 상관없이 변경

    만약 현재 캐릭터 위치가 120 .30 이면

    만약 CCMoveBy::create(2, ccp(50,10));    //현재 캐릭터 위치 기준으로 50,10만큼 이동 -> 170,40

           CCMoveTo::create(2ccp(50,10));      //좌표값에 50, 10으로 이동 -> 50,10


    Trackback 0 And Comment 0

    strncpy 로 메모리 복사

    |


    man strncpy wrote:
    The strncpy() function is similar, except that not more than n bytes of
    src are copied. Thus, if there is no null byte among the first n bytes
    of src, the result will not be null-terminated.

    이렇게 명시되어 있으니까요...

    strncpy( dst, src, n );
    dst[n] = '\0';

    정도면 되지 않을까 싶은데요 :)
    길이가 n보다 짧다면 null 까지 복사될테고... 아니라면 null terminated 라는 보장이 없으니까 후자일 경우에 한해서 문제를 일으키지 않도록 해주면 되겠죠

    '잡다한것들전부 > C, C++, C#' 카테고리의 다른 글

    추상 클래스 (C++)  (0) 2014.01.10
    Duff's Device  (0) 2014.01.10
    c++ 11 이란??  (0) 2014.01.09
    strncpy 로 메모리 복사  (0) 2014.01.07
    C언어 배열 초기화 방법  (0) 2014.01.07
    c++ stl 관련 자료  (0) 2014.01.06
    Trackback 0 And Comment 0

    C언어 배열 초기화 방법

    |

    1. int a[10] = { 0 };

    2. int a[10] = { 0, };

    3. int a[10];
       memset ( a, 0, 10 );



    1번이나 2번을 사용하자. (처음선언시) 나중에 초기화시는 무조건  MEMSET 사용

    '잡다한것들전부 > C, C++, C#' 카테고리의 다른 글

    추상 클래스 (C++)  (0) 2014.01.10
    Duff's Device  (0) 2014.01.10
    c++ 11 이란??  (0) 2014.01.09
    strncpy 로 메모리 복사  (0) 2014.01.07
    C언어 배열 초기화 방법  (0) 2014.01.07
    c++ stl 관련 자료  (0) 2014.01.06
    Trackback 0 And Comment 0