Давайте создадим клон классической Chrome Game, который появляется, когда вы офлайн.
У Chrome есть действительно простая и веселая игра, в которую вы можете играть, когда ваш Wi -Fi не работает. Он состоит из небольшого динозавра, который должен перепрыгнуть через кактусы. В этой игре есть пара основных механиков, игрок, который прыгает, когда нажимается клавиша UP, и бесконечное количество случайно сгенерированных препятствий для игрока перепрыгнуть.
Обе эти вещи могут быть легко достигнуты в Phaser, которая является 2D -игрой для создания игр в браузер HTML. Мы собираемся создать игру почти с одинаковой механикой, но с другим взглядом.
Я собираюсь называть это Жидкий
Если вы новичок в Phaser, я бы посоветовал прочитать учебное пособие по началу работы.
runny
|---assets // A folder for all our tiles and sprites
|
|---js // All the javascript files
| |--boot.js
| |--gameover.js
| |--gametitle.js
| |--main.js
| |--phaser.min.js
| |--preload.js
|
|--index.html // Where everything comes together
Для этого проекта мы будем использовать только preload.js и main.js из JS папка
Код шаблона был взят из Сайт Джошуа Маронии , скачать файлы Здесь
Нам нужны три основных вида плиток- земля, игрок и препятствия. Я буду использовать 2 разных файла PNG для препятствий и земли. Для игрока я собираюсь использовать лист спрайта, потому что его можно оживить.
Плитка земли и препятствия были сделаны Кенни и пейзаторный лист был сделан Аркс .
Здесь мы загружаем активы, которые нам нужны, прежде чем использовать их. В preload.js, изменение this.game.state.start ("Gametitle"); к this.game.state.start ("main");
Затем добавьте следующее
preload: function(){
// ground tile
this.game.load.image('tile', 'assets/tile.png');
// obstacle tile
this.game.load.image('box', 'assets/box.png');
// player sprite
this.game.load.spritesheet('player', 'assets/player.png', 24, 24, 9, -2);
}
Вот где происходит забавное!
Создавать
В функции создания мы инициализируем несколько переменных, которые мы будем использовать позже.
this.tileVelocity = -450; // velocity of the obstacles this.rate = 1500; // rate at which the obstacles appear on screen this.jumping = false; // is the player jumping? // add keyboard input this.cursors = this.game.input.keyboard.createCursorKeys(); // set a blue background color this.game.stage.backgroundColor = '479cde'; // start the phaser arcade physics system this.game.physics.startSystem(Phaser.Physics.ARCADE); // execute addObstacles at the rate we set this.timer = game.time.events.loop(this.rate, this.addObstacles, this);
Теперь нам нужно 2 группы, одна для земли и одна для препятствий.
// the floor group this.floor = this.game.add.group(); this.floor.enableBody = true; this.floor.createMultiple(Math.ceil(this.game.world.width / this.tileWidth), 'tile'); // the obstacle group this.boxes = this.game.add.group(); this.boxes.enableBody = true; this.boxes.createMultiple(20, 'box'); this.game.world.bringToTop(this.floor) this.addBase(); // add the ground for the player to run on this.createPlayer(); // add the player to the game
Окончательная функция создания
create: function() {
this.tileVelocity = -450;
this.rate = 1500;
this.jumping = false;
this.tileWidth = this.game.cache.getImage('tile').width;
this.tileHeight = this.game.cache.getImage('tile').height;
this.boxHeight = this.game.cache.getImage('box').height;
this.game.stage.backgroundColor = '479cde';
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.floor = this.game.add.group();
this.floor.enableBody = true;
this.floor.createMultiple(Math.ceil(this.game.world.width / this.tileWidth), 'tile');
this.boxes = this.game.add.group();
this.boxes.enableBody = true;
this.boxes.createMultiple(20, 'box');
this.game.world.bringToTop(this.floor)
this.addBase();
this.createPlayer();
this.cursors = this.game.input.keyboard.createCursorKeys();
this.timer = game.time.events.loop(this.rate, this.addObstacles, this);
},
Добавить базу
Теперь нашему игроку понадобится платформа для работы. Земля на самом деле не будет двигаться, поэтому мы можем просто установить фиксированное количество плиток в зависимости от размера экрана. Давайте добавим базу.
addBase: function () {
// calculate how many tiles are needed
var tilesNeeded = Math.ceil(this.game.world.width / this.tileWidth);
// the tiles should be at the bottom of the screen
var y = (this.game.world.height - this.tileHeight);
for (var i = 0; i < tilesNeeded; i++) {
// add one tile after the other
var x = i * this.tileWidth;
var tile = this.floor.getFirstDead();
tile.reset(x, y); // set the x and y coordinates
tile.body.immovable = true;
}
}
Создайте игрока
Поскольку у игрока есть что стоять, мы можем пойти дальше и создать игрока.
createPlayer: function () {
// spawn the player a to the left and a little above the ground
this.player = this.game.add.sprite(this.game.world.width/5, this.game.world.height -(this.tileHeight*2), 'player');
// depends on the size of your sprite
this.player.scale.setTo(4, 4);
this.player.anchor.setTo(0.5, 1.0);
// enable arcade physics on the player
this.game.physics.arcade.enable(this.player);
// the player has to fall down once it jumps
this.player.body.gravity.y = 2200;
this.player.body.bounce.y = 0.1;
this.player.body.drag.x = 150;
// since it is a sprite sheet, you can set animations
var walk = this.player.animations.add('walk');
// play the walk animation at 20fps
this.player.animations.play('walk', 20, true);
}
Добавьте препятствия
Просто перепрыгнуть игрока без того, чтобы перепрыгнуть, было бы довольно скучно, поэтому мы собираемся добавить несколько коробок. Если вы еще не поняли, мы не дали игроку скорость. Это потому, что игрок на самом деле не собирается двигаться, мы можем просто создать иллюзию движения, давая препятствиям скорость в направлении игрока.
Кроме того, чтобы все было интересно, высота препятствий, через которые должен перепрыгнуть игрок, является случайным, и основываясь на том, что игрок может либо сделать один прыжок, либо двойной прыжок. Мы будем реализацией функции прыжка позже.
addObstacles: function () {
// Randomly decide how tall the stack of boxes is going to be
// maximum number of tiles that the player can jump over is 4
var tilesNeeded = Math.floor( Math.random() * (5 - 0));
// slowly increase the difficulty by increasing how often boxes spawn and how fast they move
if (this.rate > 200) {
this.rate -= 10;
this.tileVelocity = -(675000 / this.rate);
}
// Add the boxes to the game
for (var i = 0; i < tilesNeeded; i++) {
// we want the boxes to be created just outside the right side of the screen
this.addBox(this.game.world.width , this.game.world.height - this.tileHeight - ((i + 1)* this.boxHeight ));
}
}
Функция выше на самом деле не добавляет коробки на карту, это сделано Добавить ящик , который создает коробку на данных координатах x и y.
addBox: function (x, y) {
// get the boxes that have already been moved outside the screen
var tile = this.boxes.getFirstDead();
tile.reset(x, y);
// set the velocity of the set of boxes
tile.body.velocity.x = this.tileVelocity;
tile.body.immovable = true;
tile.checkWorldBounds = true;
// destroy them when they go outside the screen
tile.outOfBoundsKill = true;
}
Движение
Теперь нам нужно дать игроку способ фактически перепрыгнуть через коробки, когда мы нажимаем на стрелку вверх. Об этом позаботится в Обновление Функция, которая может постоянно проверять на наличие ввода. Мы также будем реализовать механизм двойного прыжка, о котором мы говорили ранее. Это не часть оригинальной игры, но делает ее более интересной. Мы также будем проверять столкновения между другими плитками и игроком. Если игрок касается коробки, игра закончилась.
update: function() {
// collide with the floor
this.game.physics.arcade.collide(this.player, this.floor);
// collide with the boxes and call gameOver when the player hits a box
this.game.physics.arcade.collide(this.player, this.boxes, this.gameOver, null, this);
// implementing the double jump
var onTheGround = this.player.body.touching.down;
// If the player is touching the ground, let him have 2 jumps
if (onTheGround) {
this.jumps = 2;
this.jumping = false;
}
// Jump!
if (this.jumps > 0 && this.upInputIsActive(5)) {
this.player.body.velocity.y = -1000;
this.jumping = true;
}
// Reduce the number of available jumps if the jump input is released
if (this.jumping && this.upInputReleased()) {
this.jumps--;
this.jumping = false;
}
}
Есть еще 2 метода, которые нам нужно реализовать, один для проверки, если стрелка UP удерживается, и один, чтобы проверить, выпущен ли она.
// This function returns true when the player presses the "jump" control
upInputIsActive: function (duration) {
var isActive = false;
isActive = this.input.keyboard.downDuration(Phaser.Keyboard.UP, duration);
isActive |= (this.game.input.activePointer.justPressed(duration + 1000 / 60) &&
this.game.input.activePointer.x > this.game.width / 4 &&
this.game.input.activePointer.x < this.game.width / 2 + this.game.width / 4);
return isActive;
},
// This function returns true when the player releases the "jump" control
upInputReleased: function () {
var released = false;
released = this.input.keyboard.upDuration(Phaser.Keyboard.UP);
released |= this.game.input.activePointer.justReleased();
return released;
}
Для последней части нашего проекта нам нужно что -то сделать, когда игрок попадает в коробку, а игра закончилась. В этом случае, так как у нас нет стартового экрана, мы просто загрузим игру снова, то есть main.js Так положите эту строку в игра закончена
this.game.state.start('GameOver');
Если вам нужен код для этого проекта, разверните этот github Repo – Код игры динозавров
Проверьте код в действии здесь, воспроизводите его Сам – Живая демонстрация
Оригинал: “https://dev.to/aveeksaha/making-the-chrome-dinosaur-game-with-phaser-2152”