Skip to content

Instantly share code, notes, and snippets.

@kuzminT
Last active May 29, 2023 04:39
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kuzminT/3277ec2eb72b9243db73a6bc6aab956e to your computer and use it in GitHub Desktop.
Save kuzminT/3277ec2eb72b9243db73a6bc6aab956e to your computer and use it in GitHub Desktop.
Tips for phaser.js and html5 game development

Phaser

Книги:

Phaser 2

Phaser 3

Examples, reps

Phaser 3 Tips

Disable visibility change for phaser 3:

 this.game.events.off("hidden", this.game.onHidden, this.game, false);
 this.game.events.off("visible", this.game.onVisible, this.game, false) 

Обсуждение на форуме

Tweens

Tween description in docs

Tween with callbacks

 var tween = this.tweens.add({
        targets: image,
        x: 600,
        ease: 'Power1',
        duration: 3000,
        yoyo: true,
        repeat: 1,
        onStart: function () { console.log('onStart'); console.log(arguments); },
        onComplete: function () { console.log('onComplete'); console.log(arguments); },
        onYoyo: function () { console.log('onYoyo'); console.log(arguments); },
        onRepeat: function () { console.log('onRepeat'); console.log(arguments); },
    });

Animation

Current animation frame: Phaser.Utils.Array.FindClosestInSorted(0.82, gem.anims.currentAnim.frames, 'progress')

Graphics game object

Create geometry mask example

Инструменты

Ресурсы

PIXI

Build a flappy bird copy with TypeScript & Pixi.js

Typescript

Примеры игр, интересные проекты, ссылки на полезные репозитории

Books and reps

Advanced Game Design with HTML5 and JavaScript - Rex van der Spuy rep with example from book.

Tips

Создание игры с правильным соотношением сторон:

    game = new Phaser.Game(window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio, Phaser.AUTO);

Метод resize внутри state:

resize() {
            // pure javascript to scale the game
            let canvas = document.getElementById("myCanva");
            let windowWidth = window.innerWidth;
            let windowHeight = window.innerHeight;
            let windowRatio = windowWidth / windowHeight;
            let gameRatio = this.config.width / this.config.height;
            if (windowRatio < gameRatio) {
                canvas.style.width = windowWidth + "px";
                canvas.style.height = (windowWidth / gameRatio) + "px";
            }
            else {
                canvas.style.width = (windowHeight * gameRatio) + "px";
                canvas.style.height = windowHeight + "px";
            }
        }

Для расчёта расстояния между точками удобно использовать Phaser.Math.distance. Статья на тему: Finding the distance between two points in Phaser В самом js эту функция будет выглядеть так:

function (x1, y1, x2, y2) {
    var dx = x1 - x2;
    var dy = y1 - y2;
    return Math.sqrt(dx * dx + dy * dy);
  }
Кастомный билд

У Phaser 2 периодически в некоторых браузерах отображается ошибка WebGL. Чтобы исправить, нужно в исходниках Pixi найти файл src/pixi/renderers/webgl/utils/WebGLFastSpriteBatch.js. Вместо gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); поставить:

       if (shader.aTextureIndex !== -1) {
        gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20);
       }

Описание ошибки: phaserjs/phaser-ce#194

Работа со случайными числами

Метод Phaser.Math.between - returns a number between the min and max values. Ccылка на описание

Performance

Проблема - Canvas оказывается быстрее webgl.

Ссылки по теме

Atlases

Using a Texture Atlas to Optimize Your Game

Шрифты
Таймеры

Настройка событий по таймеру, forceSetTimeOut

Groups

Texture atlases, creating spritesheets

Tweens

Debugging

Configure on-device developer options - справка google по дебаггингу на андроид-устройствах.

Testing

Canvas Tips

  • Cheatsheet для canvas

  • HTML5 Canvas Rounded Corners Tutorial - draw rounded box with arcTo() and lines.

    // Drow ellipse by pure canvas
    function drawEllipse(ctx, x, y, a, b) {
       // Запоминаем положение системы координат (CК) и масштаб
      ctx.save();
      ctx.beginPath();
    
      // Переносим СК в центр будущего эллипса
      ctx.translate(x, y);
    
      /*
       * Масштабируем по х.
       * Теперь нарисованная окружность вытянется в a / b раз
       * и станет эллипсом
       */
    
      ctx.scale(a / b, 1);
    
      // Рисуем окружность, которая благодаря масштабированию станет эллипсом
      ctx.arc(0, 0, b, 0, Math.PI * 2, true);
    
      // Восстанавливаем СК и масштаб
      ctx.restore();
    
      ctx.closePath();
      ctx.stroke();
    }
    

Geometry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment