HTML5GAME :: HTML5GAME

달력

82025  이전 다음

  • 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
  • 31

Phaser Js 기본 타이머 사용 설명서 


타이머는 게임 개발의 큰 부분을 합니다. 플레이어가 메시지를 읽을 때까지 몬스터를 공개하거나 게임의 다음 부분이 나타나는 주기를 설정할 수 있습니다. 또한 타이머를 사용하여 카운트 업 또는 카운트 다운 할 수 있습니다.


자 이제 Phaser js에서 사용할수 있는 타이머를 확인해 보겠습니다.


원샷 타이머

원샷 타이머는 지정된 시간 (초) 후에 이벤트를 한 번 실행하는 타이머입니다. 지연 타이머로 생각할 수도 있습니다. 아래의 예제는 5 초 후에 delayOver 함수를 호출합니다.

game.time.events.add (Phaser.Timer.SECOND * 5, this.delayOver, this);



루핑 타이머

루핑 타이머는 원샷과 거의 같은 방식으로 작동하지만 멈출 때까지 기능을 계속 실행합니다. 이 코드는 초마다 addMonster라는 함수를 호출합니다.

game.time.events.loop (Phaser.Timer.SECOND, this.addMonster, this);



타이머 멈춤

타이머를 정지 시키려면 먼저 변수에 할당하여 참조를 추가해야합니다.

this.monsterTimer = game.time.events.loop (Phaser.Timer.SECOND, this.addMonster, this);

그런 다음 타이머를 멈추고 싶을 때 다음과 같이 타이머를 끌 수 있습니다 :

game.time.events.remove (this.monsterTimer);



시간 조정

Phaser 타이머는 밀리 초 단위로 측정됩니다. 1000 밀리 초는 1 초와 같습니다. Phaser.Timer.SECOND를 사용하는 것은 첫 번째 매개 변수로 1000을 배치하는 것과 동일하지만 상수를 사용하면 더 쉽게 읽을 수 있습니다. 이 상수를 곱하거나 나눔으로써 함수가 호출되는 빈도를 조정할 수 있습니다.

Phaser.Timer.SECOND = 1 초

Phaser.Timer.SECOND * 5 = 5 초

Phaser.Timer.SECOND / 2 = 0.5 초 또는 함수를 초당 두 번 호출

Phaser.Timer.SECOND / 10 = 10 분의 1 초



카운트 다운 타이머 만들기

레벨이나 게임을 완료하기 위해 일정 시간 (분 또는 초)을 사용자에게 부여하려고한다고 가정 해보십시오. 게임을 끝내기 위해 원샷 타이머를 설정하면됩니다. 그러나 남은 시간 (초)을 표시하려면 카운트 다운 시계를 설정해야합니다. 우리는 초를 잡아두고 루프 타이머에서 초당 하나를 뺀 변수를 설정함으로써 이것을 할 수 있습니다. 초를 초로 변환 할 수도 있습니다. 다음은 이를 수행 할 수있는 몇 가지 샘플 코드입니다.



var StateMain = {

    preload: function() {},

    create: function() {

        //total time until trigger

        this.timeInSeconds = 120;

        //make a text field

        this.timeText = game.add.text(game.world.centerX, game.world.centerY, "0:00");

        //turn the text white

        this.timeText.fill = "#ffffff";

        //center the text

        this.timeText.anchor.set(0.5, 0.5);

        //set up a loop timer

        this.timer = game.time.events.loop(Phaser.Timer.SECOND, this.tick, this);

    },

    tick: function() {

        //subtract a second

        this.timeInSeconds--;

        //find how many complete minutes are left

        var minutes = Math.floor(this.timeInSeconds / 60);

        //find the number of seconds left

        //not counting the minutes

        var seconds = this.timeInSeconds - (minutes * 60);

        //make a string showing the time

        var timeString = this.addZeros(minutes) + ":" + this.addZeros(seconds);

        //display the string in the text field

        this.timeText.text = timeString;

        //check if the time is up

        if (this.timeInSeconds == 0) {

            //remove the timer from the game

            game.time.events.remove(this.timer);

            //call your game over or other code here!

            this.timeText.text="Game Over";

        }

    },

    /**

     * add leading zeros to any number less than 10

     * for example turn 1 to 01

     */

    addZeros: function(num) {

        if (num < 10) {

            num = "0" + num;

        }

        return num;

    },

    update: function() {}

}


Posted by 마스터킹
|



이 간단한 Phaser 튜토리얼은 심플한 2D 플랫폼을 만드는 방법을 보여줍니다.


이 튜토리얼에서는 이미 Phaser에 익숙하다고 가정합니다.  만약에 익숙하지 않으면 먼저 Phaser Js 로 Flappy Bird 만들기 - 1 과 Phaser Js 로 Flappy Bird 만들기 - 2 를 확인해 하시면 됩니다.


기본적으로 빈 페이저 프로젝트 인 게임의 구조를 만들어 보겠습니다.

// 전체 게임을 포함 할 상태 만들기
var mainState = {
preload: function() {
// 여기에 자산을 미리로드합니다.
},

create: function() {
// 여기에 게임을 만듭니다.
},

update: function() {
// 게임을 초당 60 회 업데이트합니다.
},
};

// 게임 초기화 및 상태 시작
var game = new Phaser.Game(500, 200);
game.state.add('main', mainState);
game.state.start('main');


create () 함수름 다음과 같이 변경하여 게임 설정을 합니다.

    create: function() {
// 배경색을 파란색으로 설정하십시오.
game.stage.backgroundColor = '#3598db';
// 아케이드 물리 시스템을 시작하십시오 (이동 및 충돌 용).
game.physics.startSystem(Phaser.Physics.ARCADE);
// 모든 게임 개체에 물리 엔진 추가
game.world.enableBody = true;
},


그리고 preload () 함수에서 다음과 같이 사용하는 스프라이트를 로드합니다.

    preload: function() {
// 여기에 자산을 미리로드합니다.
game.load.image('player', 'assets/player.png');
game.load.image('wall', 'assets/wall.png');
game.load.image('coin', 'assets/coin.png');
game.load.image('enemy', 'assets/enemy.png');
},



화살표 키로 제어 할 수있는 플레이어를 추가해 봅시다.

그래서 다음 코드를 create () 함수에 추가하십시오.

        // 화살표 키를 저장하는 변수
this.cursor = game.input.keyboard.createCursorKeys();
// 플레이어 만들기
this.player = game.add.sprite(70, 100, 'player');
// 중력을 가하여 떨어 뜨립니다.
this.player.body.gravity.y = 600;


그리고 다음 코드를 update () 함수에 추가합니다.

        // 화살표 키를 누르면 플레이어가 움직입니다.
if (this.cursor.left.isDown)
this.player.body.velocity.x = -200;
else if (this.cursor.right.isDown)
this.player.body.velocity.x = 200;
else
this.player.body.velocity.x = 0;

// 플레이어가 땅에 닿으면 점프하게하십시오.
if (this.cursor.up.isDown && this.player.body.touching.down)
this.player.body.velocity.y = -250;


다음 단계는 플레이어에게 레벨을 부여하는 것입니다. create () 함수에서 다음과 같이 설정합니다.

        // 객체를 포함 할 3 개의 그룹을 만듭니다.
this.walls = game.add.group();
this.coins = game.add.group();
this.enemies = game.add.group();

// 레벨을 디자인하십시오. x = 벽, o = 동전,! = 용암.
var level = [
'xxxxxxxxxxxxxxxxxxxxxx',
'! ! x',
'! o x',
'! o x',
'! x',
'! o ! x x',
'xxxxxxxxxxxxxxxx!!!!!x',
];

// 배열을 통해 레벨 만들기
for (var i = 0; i < level.length; i++) {
for (var j = 0; j < level[i].length; j++) {

// 벽을 만들어 '벽'그룹에 추가하십시오.
if (level[i][j] == 'x') {
var wall = game.add.sprite(30+20*j, 30+20*i, 'wall');
this.walls.add(wall);
                    wall.body.immovable = true;
                }

// 동전을 만들어 '동전'그룹에 추가하십시오.
else if (level[i][j] == 'o') {
var coin = game.add.sprite(30+20*j, 30+20*i, 'coin');
this.coins.add(coin);
}

// 적을 만들어 '적'그룹에 추가하십시오.
else if (level[i][j] == '!') {
var enemy = game.add.sprite(30+20*j, 30+20*i, 'enemy');
this.enemies.add(enemy);
}
}
}


마지막으로 update () 함수에서 이와 같은 플랫폼 작성자의 모든 충돌을 처리해야합니다.

        // 플레이어와 벽을 충돌 시키십시오.
game.physics.arcade.collide(this.player, this.walls);

// Call the 'takeCoin' function when the player takes a coin
game.physics.arcade.overlap(this.player, this.coins, this.takeCoin, null, this);

// Call the 'restart' function when the player touches the enemy
game.physics.arcade.overlap(this.player, this.enemies, this.restart, null, this);


그리고이 두 가지 새로운 기능을 추가해야합니다.

    // 동전 제거 함수
takeCoin: function(player, coin) {
coin.kill();
},

// 게임 재시작 함수
restart: function() {
game.state.start('main');
}



여기에 우리가 함께 만든 작은 2D 플랫폼이 있습니다.



Posted by 마스터킹
|


오늘은 Phaser js 로 간단한 브레이크 아웃(일명: 벽돌깨기) 게임을 만들어 보겠습니다.


이 튜토리얼에서는 이미 Phaser에 익숙하다고 가정합니다.  만약에 익숙하지 않으면 먼저 Phaser Js 로 Flappy Bird 만들기 - 1 과 Phaser Js 로 Flappy Bird 만들기 - 2 를 확인해 하시면 됩니다.


기본적으로 빈 페이저 프로젝트 인 게임의 구조를 만들어 보겠습니다.

// 전체 게임을 포함 할 상태 만들기
var mainState = {
preload: function() {
// 여기에 Asset 을 미리로드합니다.
},

create: function() {
// 여기에 게임을 만듭니다.
},

update: function() {
// 게임을 초당 60 회 업데이트합니다.
},
};

// 게임 초기화 및 상태 시작
var game = new Phaser.Game(400, 450);
game.state.add('main', mainState);
game.state.start('main');


그리고 이것을 create () 함수 안에 추가하여 게임 설정을 할 수 있습니다.

// 배경색을 파란색으로 설정하십시오.
game.stage.backgroundColor = '#3598db';

// 아케이드 물리 시스템을 시작하십시오 (이동 및 충돌 용).
game.physics.startSystem(Phaser.Physics.ARCADE);

// 모든 게임 개체에 물리 엔진 추가
game.world.enableBody = true;


이 튜토리얼의 나머지 부분에서는 mainState 내부의 코드에만 초점을 맞출 것입니다.


화살표 키로 제어 할 수있는 패들을 추가합시다. 아래에서 변경된 코드 만 작성 했으므로 이전에 추가 한 설정이없는 경우 놀라지 마십시오.

preload: function() {
game.load.image('paddle', 'assets/paddle.png');
},

create: function() {
// 왼쪽 / 오른쪽 화살표 키 만들기
this.left = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
this.right = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);

// 화면 하단에 패들을 추가하십시오.
this.paddle = game.add.sprite(200, 400, 'paddle');

// 패들이 공을 때리면 움직이지 않도록하십시오.패들이 공을 때리면 움직이지 않도록하십시오.
this.paddle.body.immovable = true;
},

update: function() {
// 화살표 키를 누르면 패들을 왼쪽 / 오른쪽으로 움직입니다.화살표 키를 누르면 패들을 왼쪽 / 오른쪽으로 움직입니다.
if (this.left.isDown) this.paddle.body.velocity.x = -300;
else if (this.right.isDown) this.paddle.body.velocity.x = 300;

// 아무 키도 누르지 않으면 패들 정지아무 키도 누르지 않으면 패들 정지
else this.paddle.body.velocity.x = 0;
},


이제 상단에 5x5 벽돌을 추가하겠습니다. 다시 말하면, 변경된 코드 만 아래에 쓰여 있습니다.

preload: function() {
game.load.image('brick', 'assets/brick.png');
},

create: function() {
// 모든 벽돌을 포함 할 그룹을 만듭니다.
this.bricks = game.add.group();

// 그룹에 25 개의 벽돌을 추가하십시오 (5 열과 5 줄).
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 5; j++) {
// 정확한 위치에 벽돌 만들기
var brick = game.add.sprite(55+i*60, 55+j*35, 'brick');

// 공이 그것을 때릴 때 벽돌이 움직이지 않도록하십시오.
brick.body.immovable = true;

// 그룹에 브릭 추가
this.bricks.add(brick);
}
}
},


다음으로 튀는 공을 추가합시다.

preload: function() {
game.load.image('ball', 'assets/ball.png');
},

create: function() {
// 공 추가
this.ball = game.add.sprite(200, 300, 'ball');

// 공에 속도 추가
this.ball.body.velocity.x = 200;
this.ball.body.velocity.y = 200;

// 공이 튀어 오를지 확인
this.ball.body.bounce.setTo(1);
this.ball.body.collideWorldBounds = true;
},


마지막으로 우리 게임에서 모든 충돌을 처리해야합니다.

preload: function() {
game.load.image('ball', 'assets/ball.png');
},

create: function() {
// 공 추가
this.ball = game.add.sprite(200, 300, 'ball');

// 공에 속도 추가
this.ball.body.velocity.x = 200;
this.ball.body.velocity.y = 200;

// 공이 튀어 오를지 확인
this.ball.body.bounce.setTo(1);
this.ball.body.collideWorldBounds = true;
},

update: function() {
// 패들과 볼 사이에 충돌을 추가합니다.
game.physics.arcade.collide(this.paddle, this.ball);

// 공이 벽돌에 닿으면 'hit'기능 호출
game.physics.arcade.collide(this.ball, this.bricks, this.hit, null, this);

// 공이 패들 아래에 있으면 게임을 다시 시작하십시오.
if (this.ball.y > this.paddle.y)
game.state.start('main');
},

// 게임에서 벽돌을 제거하는 함수
hit: function(ball, brick) {
brick.kill();
},


그리고 실행을 하면



50 줄 미만의 코드를 사용하면 간단한 브레이크 아웃 클론을 만들어 보았습니다.



Posted by 마스터킹
|