Cocos Creator

[예제 게임] 씬 전환과 버튼 클릭 이벤트

밀하우스 마나스톰 2021. 5. 31. 16:13

 

버튼을 누르면 씬 전환이 이뤄지도록 한다.

 

다음 씬인 GameScene을 만들고, 버튼에 붙여줄 StartGameButton.ts 스크립트를 만든다.

 

그리고 TitleScene의 로직을 작성할 TitleScene.ts 스크립트로 만들어준다.

 

(참고로 앞으로 대부분의 스크립트는 타입 스크립트로 작성할 것이다)

 

 

// TitleScene.ts

const {ccclass, property} = cc._decorator;

@ccclass
export default class TitleScene extends cc.Component {
    start () {
        cc.director.preloadScene("GameScene");
    }
}

 

타이틀 씬의 로직은 별다른건 없고, 다음 씬인 GameScene을 미리 로드한다.

 

Node Tree 뷰에서 빈 오브젝트를 만들고 TitleScene 스크립트를 붙여준다. 

 

 

 

 

cc.director.preloadScene 함수의 summary를 보면 파라미터로 로드할 씬 이름과 더불어

 

현재 데이터를 얼마만큼 로드됐는지, 로드할 데이터의 총 개수 등이 들어가는 것으로 알 수 있다.

 

 

 

    update(dt)
    {
        cc.loader.onProgress = (completedCount, totalCount, item) => {
            if (this.progressLabel) {
              var percent = 0;
              if (totalCount > 0) {
                percent = 100 * completedCount / totalCount;
              }
              this.progressLabel.string = Math.round(percent) + '%';
            }
          };
    }

 

이런식으로 cc.loader.onProgress 함수를 통해서 completedCount와 totalCount에 접근할 수 있고

 

로딩 퍼센트나 게이지를 만들 수 있다. 하지만 이 프로젝트에서는 쓰지는 않을 예정.

 

 

 

// StartGameButton.ts

const {ccclass, property} = cc._decorator;

@ccclass
export default class StartGameButton extends cc.Component {

    StartGame()
    {
        cc.director.loadScene("GameScene");
    }
}

 

StartGameButton.ts에 StartGame() 함수를 작성한다. 다음 씬인 GameScene으로 씬 전환을 하는 함수다.

 

그리고 버튼을 눌렀을 때, 이 StartGame() 함수를 실행하도록 하는 방법은 세 가지가 있다.

 

 

(1) Properties 뷰를 통해 이벤트 등록

 

 

Properties 뷰에서 StartGameButton의 Button 컴포넌트를 보면 가장 아래에 Click Events가 있다.

 

 

 

쉽게 말해서 1~3은, 노드 ⊃ 스크립트 컴포넌트 ⊃ 콜백 함수 구조에서 원하는 콜백 함수를 찾기 위한 속성들이다. 

 

참고로 Component는 클래스 이름이 아닌 스크립트 이름을 뜻한다.

 

그리고 CustomEventData는 해당 이벤트에 id값을 부여할 수 있다.

 

나중에 어떤 노드의 이벤트 목록을 순회할 때 그 id값으로 특정 이벤트를 찾을 수 있다.

 

 

(2) cc.Node의 on을 통해 이벤트 등록

 

    start () {
        this.node.on("click", this.StartGame, this);
    }

 

이 버튼(Node)이 가지고 있는 이벤트 리스트에 새 이벤트를 추가한다.

 

파라미터는 차례대로 이벤트 트리거의 이름, 콜백 함수, 콜백 함수를 실행할 객체를 의미한다.

 

트리거 이름은 "click" 대신에 "touchend"를 사용해도 된다.

 

    start () {
        this.node.on("click", function(){
            cc.director.loadScene("GameScene");
        }, this);
    }

 

그리고 콜백 함수는 람다식으로 작성할 수도 있다. 

 

 

(3) 직접 이벤트를 생성하고 이벤트 리스트에 추가

 

    start () {
        var handler = new cc.Component.EventHandler();
        handler.target = this.node;
        handler.component = "StartGameButton";
        handler.handler = "StartGame"
        handler.customEventData = null;

        this.node.getComponent(cc.Button).clickEvents.push(handler);
    }

 

(1)에서 에디터의 Properties 뷰에서 했던 작업을 스크립트로 직접 하는 것이다.