크리티컬섹션 :: Phaser Js 와 클래스(Class)

달력

92024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

자바스크립트 클래스


나는 바위 밑에서 살고있는 것처럼 느껴진다.

Javascript 클래스는 1 년 넘게 사용하었습니다. 이것은 모든 것을 바꿉니다! 설명하겠습니다.


지난 16 년 동안 게임을 만드는 대부분의 시간은 Flash를 사용하여 이루어졌습니다. Flash의 Actionscript 언어에 대한 좋은 점 중 하나는 그것이 매우 잘 구조화되어 있다는 것입니다. 클래스를 사용하고, 다른 클래스를 확장하고, 잘 관리 할 수있는 부분으로 분류 할 수 있습니다. 

html5로 옮기기에 대한 나의 가장 큰 반대 중 하나는 클래스가 없었기 때문입니다. 우리는 항상 javascript 클래스를 다음과 같이 사용할수 있습니다.

function Apple (type) {

    this.type = type;

    this.color = "red";

}

Apple.prototype.getInfo = function() {

    return this.color + ' ' + this.type + ' apple';

};

var myApple=new Apple("macintosh");

console.log(myApple.getInfo());


자, 이것은 완벽하게 잘 작동했습니다. 문제는 대부분 정리할 수있는 문제 중 하나였습니다. 이 방법으로 계속 작성했거나 복잡한 개체에 대한 이 게시물에서 사용한 것과 비슷한 개체를 반환하는 함수를 사용했습니다.


그러나, 방금 Javascript에서 실제 클래스를 사용할 수 있다는 것을 알았습니다. 기술적으로 내가 읽은 바로는 이것이 "Syntax Sugar"라는 것입니다. Javascript에서는 모든 것이 똑같이 작동하지만, 다르게 쓸 수는 있습니다. 그것은 나를 위해 충분합니다. 이제 우리는 apple 클래스를 다음과 같이 작성할 수 있습니다.

Class Apple

{

constructor(type)

{

    this.type=type;

    this.color=red;

}

getInfo()

{

   return this.color + ' ' + this.type + ' apple';

}

} 

var myApple=new Apple("macintosh");

console.log(myApple.getInfo());


Phaser 에서 클래스 사용하기

자, Phaser가 무엇을 의미합니까?

그것은 우리가 할 수있는 것을 의미합니다 :

- Phaser 클래스를 확장하는 클래스 작성

- 훨씬 더 재사용 가능한 코드 작성하기

- 코드를보다 효율적으로 정리


그리드 만들기!

예를 들어, 많은 게임과 프로젝트에 그리드가 필요합니다. 그리드에는 객체가 추가되어야하고 객체를 행과 열로 정렬해야합니다. Phaser에서는 그룹을 사용하여 각 개체를 그룹에 추가 한 다음 forEach를 사용하여 그룹 전체를 반복합니다. 그리드를 사용해야 할 때마다 프로젝트 폴더에 복사 할 수있는 클래스를 작성하고 싶습니다.


먼저 Grid라는 클래스를 만들어야합니다.

class Grid {

    constructor() {    

    }

}

두 번째 단계는 Grid 클래스가 Phaser의 그룹 클래스를 확장하도록 만드는 것입니다. 

extends 키워드를 사용하여이 작업을 수행 할 수 있습니다.


Phaser의 그룹 클래스는 Grid 클래스의 부모가됩니다.

class Grid extends Phaser.Group {

    constructor() {         

    }

}


마지막 단계는 super 명령을 사용하고 게임의 인스턴스를 매개 변수로 전달하여 부모 (Phaser.Group)의 생성자를 호출하는 것입니다. 이것은 "game"이라는 Phaser 게임 내에서 코드를 실행한다고 가정합니다. super가 생성자 내부에서 호출되는 첫 번째 것이 맞는지 확인하십시오.

class Grid extends Phaser.Group {

    constructor() {

     super(game);  

    }

}


현재 우리의 그리드는 Phaser 그룹보다 더 많은 것을하지 않습니다. 그런데 왜이 곤경에 가야합니까? 이제 우리는 우리 자신의 사용자 정의 함수와 변수를 추가 할 수 있습니다!


먼저 "cols"라는 생성자에 매개 변수를 전달하여 그리드에 포함시킬 열 수를 표시 한 다음이를 클래스 변수로 설정해 보겠습니다.

class Grid extends Phaser.Group {

    constructor(cols) {

     super(game);  

     this.cols=cols;

    }

}


항목을 추가 한 후에는 그리드에 정렬해야하므로 이제 해당 기능을 만들어 보겠습니다. 참고 : 이것은 동일한 크기의 항목에서만 잘 작동합니다.

arrange()

    {

     //current row count

     var row=0;

     //current column count

     var col=0;

     //use the group's built in for each to loop

     //through all the children

     this.forEach(function(item)

     {

     //set the position based

     //on the row, the column

     //and the height of the item

     item.y=row*item.height;

     item.x=col*item.width;

 

     //advance the column count

     col++;

     //if the column count is equal to the

     //number of columns set

     if (col==this.cols)

     {

     //go to the next row

     row++;

     //reset the column to 0

     col=0;

     }

     }.bind(this));

     //use bind(this) to keep the 'this' keyword

     //to mean the class

    }


이제 다음과 같이 그리드 클래스를 사용할 수 있습니다.

var grid=new Grid(3);

//add nine sprites

grid.add(sprite1);

....

grid.add(sprite9);

grid.arrange();


스프라이트를 확장하는 것은 어떨까요?


조금 더 많은 작업이 필요하지만 다음과 같이 할 수 있습니다.

class LetterBox extends Phaser.Sprite {

    constructor() {

     super(game,0,0,"letters",0);

 

     //add to stage right away

     game.add.existing(this);

    }

    }


스프라이트의 슈퍼 생성자에서 매개 변수는 다음과 같습니다.

super(game,x,y,"library_key",frame_number);


game.add.existing은 호출 한 후 곧바로 스프라이트를 스테이지에 추가합니다.

var letter=new LetterBox();


클래스의 인스턴스를 그룹에 추가하려는 경우 생략 할 수 있습니다.


다음은 Grid 및 LetterBox 클래스와 몇 가지 추가 함수가 추가 된 예제입니다.


StateMain.js

var StateMain = {

    preload: function() {

        //preload the sprite sheet

        game.load.atlasJSONHash('letters', "images/letters.png", "images/letters.json");

    },

    create: function() {

        //make a new grid

        //with 5 columns

        //

        var grid = new Grid(5);

        //

        //make 25 letter boxes

        //

        for (var a = 0; a < 25; a++) {

            //

            //make a new letter box

            //

            var lb = new LetterBox();

            //

            //set a random letter

            //

            lb.setRand();

            //

            //add the letter to the grid

            //

            grid.add(lb);

        }

        //arrange the grid

        grid.arrange();

        //fit to the stage

        grid.fitStage();

        //put the grid in the center

        grid.center();

    },

    update: function() {}

}


The Grid Class – grid.js

class Grid extends Phaser.Group {

    constructor(cols) {

        super(game);

        this.cols = cols;

    }

    arrange() {

        //current row count

        var row = 0;

        //current column count

        var col = 0;

        //use the group's built in for each to loop

        //through all the children

        this.forEach(function(item) {

            //set the position based

            //on the row, the column

            //and the height of the item

            item.y = row * item.height;

            item.x = col * item.width;

            //advance the column count

            col++;

            //if the column count is equal to the

            //number of columns set

            if (col == this.cols) {

                //go to the next row

                row++;

                //reset the column to 0

                col = 0;

            }

        }.bind(this));

        //use bind(this) to keep the 'this' keyword

        //to mean the class

    }

    fitStage(per = 100) {

        this.width = game.width * (per / 100);

        this.scale.y = this.scale.x;

    }

    center() {

        this.x = game.width / 2 - this.width / 2;

        this.y = game.height / 2 - this.height / 2;

    }

}


The Letter Box Class – letterBox.js

class LetterBox extends Phaser.Sprite {

    constructor() {

        super(game, 0, 0, "letters", 0);

        //add to stage right away

        //game.add.existing(this);

    }

    /**

     * set by passing a lower case letter

     */

    setLetter(letter) {

        var index = letter.charCodeAt(0);

        this.frame = index - 97;

    }

    /**

     * set a random letter

     */

    setRand() {

        var index = game.rnd.integerInRange(0, 26);

        this.frame = index;

    }

}


Posted by 마스터킹
|