Frontend/Cocos Creator

[Cocos Creator] cc.Class 파헤치기

에반황 2017. 11. 21. 15:36

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;
        }
    }
}


반응형