[Cocos Creator] cc.Class 파헤치기

2017. 11. 21. 15:36· Frontend/Cocos Creator
목차
  1. cc.Class로 class 정의하기
  2. CCClass 정의하기
  3. 초기화 (Instantiation)
  4. 클래스 판단 (Judge class)
  5. Constructor
  6. Instance method
  7. 상속 (Inheritance)
  8. Superclass constructor
  9. Property 정의
  10. 간단한 declaration
  11. 복잡한 declaration
  12. Array declaration
  13. get/set declaration

cc.Class로 class 정의하기

Cocos Creator에서는 Class를 만들 수 있는 cc.Class라는 유용한 API를 제공하고 있습니다. 


CCClass 정의하기

cc.Class를 생성할 때 인자로 prototype 객체 (key-value로 필요한 파라미터들이 지정된)를 넘김으로서 class를 만들어냅니다.

var Sprite = cc.Class({
    name: "sprite"
});

위 코드는 class를 만들어서 Sprite 변수에 넣고 있습니다. 게다가 클래스 이름을 "sprite"로 지정까지 했죠. Class Name은 일반적으로 생략될 수 있습니다. (직렬화 (serialization)에 사용됩니다.) 


초기화 (Instantiation)

위에서 정의한 Sprite 변수는 Javascript construcor로 배정됩니다. 새로운 object를 만드는데 사용할 수 있죠.

var obj = new Sprite();


클래스 판단 (Judge class)

object의 클래스를 판단하고 싶을 때 JavaScript built-in 문법인 instanceof를 사용하면 됩니다.

cc.log(obj instanceof Sprite);       // true


Constructor

생성자를 정의하기 위해선 다음의 문법을 사용 ctor:

var Sprite = cc.Class({
    ctor: function () {
        cc.log(this instanceof Sprite);    // true
    }
});


Instance method

var Sprite = cc.Class({
    // instance method "print"를 정의하는 방법
    print: function () { }
});


상속 (Inheritance)

이미 정의된 클래스를 extend하기 위해 다음의 문법을 사용 extends:

// base class
var Shape = cc.Class();

// sub class
var Rect = cc.Class({
    extends: Shape
});


Superclass constructor

Super class의 생성자는 따로 호출해줄 필요 없이 child class가 생성되기 직전에 호출됩니다.

var Shape = cc.Class({
    ctor: function () {
        cc.log("Shape");    // superclass constructor는 자동적으로 호출될 것임
    }
});

var Rect = cc.Class({
    extends: Shape
});

var Square = cc.Class({
    extends: Rect,
    ctor: function () {
        cc.log("Square");   // 이후에 childlcass의 constructor가 호출됨    }
});

var square = new Square();

위 코드의 output은 "Shape" 그리고 "Square"가 나올 입니다.


Property 정의

component에 attribute(property)를 정의함으로서 우리는 visible하게 에디터의 component에서 property들을 볼 수 있습니다. 에디터에서 쉽게 값을 정의하거나 할당할 수 있는 것 입니다.

attribute를 정의하기 위해서 해야되는 것은 cc.Class에 정의되어 있는 properties에 key-value로 넣기만 하면 됩니다. 

cc.Class({
    extends: cc.Component,
    properties: {
        userID: 20,
        userName: "Foobar"
    }
});

A저장하면 즉시 에디터의 Component에서 프로퍼티들을 볼 수 있게되죠.

properties-in-inspector

Cocos Creator에서, 두 가지의 정의 방법을 제공하고 있습니다.


간단한 declaration

대부분 우리는 간단한 정의만 필요할 것 입니다.

  • Javascript 원시(Primitive)타입 프로퍼티가 필요할 때:

      properties: {
          height: 20,       // number
          type: "actor",    // string
          loaded: false,    // boolean
          target: null,     // object
      }
    
  • property가 타입을 가지고 있을 때(cc.Node, cc.Vec etc.)는 선언 시 그 객체의 생성자를 적어줘야합니다.

      properties: {
          target: cc.Node,
          pos: cc.Vec2,
      }
    
  • 선언할 property의 타입이 cc.ValueType(cc.Vec2, cc.Color, cc.Size etc.)을 상속했다면 생성자를 넣는 것 뿐만 아니라 instance 자체를 다음과 같이 할당할 수 있습니다.

      properties: {
          pos: new cc.Vec2(10, 20),
          color: new cc.Color(255, 255, 255, 128),
      }
    
  • property가 배열로 선언된다면 내부에 어떤 타입이 들어올 수 있는지도 지정할 수 있습니다.

      properties: {
          any: [],      // array of arbitrary type
          bools: [cc.Boolean],
          strings: [cc.String],
          floats: [cc.Float],
          ints: [cc.Integer],
    
          values: [cc.Vec2],
          nodes: [cc.Node],
          frames: [cc.SpriteFrame],
      }
    

Note: 위의 상황들에 속하지 않는다면 다음의 복잡한 선언을 사용하세요.


복잡한 declaration

properties: {
    score: {
        default: 0,
        displayName: "Score (player)",
        tooltip: "The score of player",
    }
}

위 코드엔 세개의 attribute가 명시되어 있습니다. 차근히 하나씩 분석해보자면 score의 defualt 값은 0이고, Properties 패널에 나타낼 property의 이름은 "Score (player)"이며, 커서를 property에 올렸을 때 보여줄 팁을 적은 것 입니다.

아래에 일반적으로 사용하는 attribute들이 있습니다.

  • default: 프로퍼티의 default 값을 지정하고, 이 값은 node에 컴포넌트를 붙이는 첫 순간에만 사용됩니다.
  • type: 프로퍼티의 타입을 제한합니다. CCClass Advanced Reference: type attribute에서 자세한 정보 확인
  • visible: 패널에서 보일지 안 보일지를 지정할 수 있습니다.
  • serializable: false로 지정하면 serialize하지 않음.
  • displayName: 패널에 보일 property명 지정.
  • tooltip:  팁 추가.

더 자세한 정보는 다음에서 확인 Property attribute.


Array declaration

default는 무조건 [ ]로 지정해야합니다.

properties: {
    names: {
        default: [],
        type: [cc.String]   
    },

    enemies: {
        default: [],
        type: [cc.Node]    
    },
}


get/set declaration

get/set 을 지정해 놓으면 propert에 접근할 때 미리 정의된 메소드가 트리거되게 할 수 있습니다.properties: {

    width: {
        get: function () {
            return this._width;
        },
        set: function (value) {
            this._width = value;
        }
    }
}


반응형
저작자표시 (새창열림)

'Frontend > Cocos Creator' 카테고리의 다른 글

[Cocos Creator] Layout 개념 및 사용 예시  (0) 2018.01.29
[Cocos Creator] ScrollView 개념 및 사용 예시  (2) 2018.01.29
[Cocos Creator] Decorator 사용하기  (0) 2018.01.04
[Cocos Creator] 생명주기 (Life Cycle)  (0) 2017.11.21
[Cocos Creator Animation] 1. Animation에 대하여  (0) 2017.10.27
[Cocos Creator 강좌] RichText 사용하기  (0) 2017.10.19
  1. cc.Class로 class 정의하기
  2. CCClass 정의하기
  3. 초기화 (Instantiation)
  4. 클래스 판단 (Judge class)
  5. Constructor
  6. Instance method
  7. 상속 (Inheritance)
  8. Superclass constructor
  9. Property 정의
  10. 간단한 declaration
  11. 복잡한 declaration
  12. Array declaration
  13. get/set declaration
'Frontend/Cocos Creator' 카테고리의 다른 글
  • [Cocos Creator] ScrollView 개념 및 사용 예시
  • [Cocos Creator] Decorator 사용하기
  • [Cocos Creator] 생명주기 (Life Cycle)
  • [Cocos Creator Animation] 1. Animation에 대하여
에반황
에반황
"어른이면서 애이기도 하고 싶다."
에반황
에반, 어른반
에반황
전체
오늘
어제
  • 전체보기 (118)
    • About (1)
    • Backend (5)
      • Django (3)
      • Spring (2)
    • Database (2)
      • 아키텍처 (0)
      • SQL (0)
      • Redis (2)
      • 코딩 테스트 (0)
      • 요구 사항 해결 (0)
    • Infra, Cloud (0)
      • AWS (0)
      • GoCD (0)
      • Docker (0)
      • Kubernetes (0)
      • Mesos Marathon (0)
    • Basic (34)
      • C (1)
      • C# (4)
      • C++ (1)
      • Java (9)
      • Javascript (6)
      • Typescript (5)
      • GO (0)
      • Python (4)
      • 프로그래밍 기초 (1)
      • 게임 디자인 패턴 (1)
      • 운영체제 (0)
      • 알고리즘 (2)
      • 자료구조 (0)
    • Computer Science (0)
    • Frontend (74)
      • Swift (1)
      • Unity (31)
      • Android (13)
      • Vue.js (2)
      • Phaser (1)
      • Cocos2D JS (2)
      • Cocos Creator (16)
      • Facebook Instant Game (8)
반응형

인기 글

최근 댓글

hELLO · Designed By 정상우.v4.2.2
에반황
[Cocos Creator] cc.Class 파헤치기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.