微信小遊戲體驗之打飛機改造計劃

楓~風發表於2018-01-03

微信小遊戲推出已有幾天了,這個功能對小程式和小遊戲的推動影響不用多說,大家趕緊摩拳擦掌往上擼就可以了。關於如何開發官方文件已經說明了,這篇則是對官方的打飛機demo一些小改造。

開發預備式

  1. 下載最新版本的微信開發者工具(v1.02.1712280)
  2. 根據官方文件說明,目前不提供公開註冊。因此目前只能使用無AppID模式進行體驗
  3. 為了讓HTML5遊戲輕鬆接入,官方提供了Adapter。這個的作用就是提供HTML5寫法和wx寫法的全域性轉換層。

打飛機小遊戲

使用無AppID模式建立一個微信小遊戲後可以看到官方demo,其中入口檔案和配置檔案:game.jsgame.jsongame.js引入並初始化包含整個打飛機的遊戲場景、參與者(玩家飛機和敵方飛機)、遊戲邏輯的主函式的main.js。在main.js中我們可以發現由於Adapter的存在,這裡的程式碼和我們平常的程式碼寫法沒什麼差異了。遊戲的主邏輯如下圖:

image

在loop中,玩家每隔20幀射一次,每隔60幀生成新的敵機。每幀檢查玩家和敵機是否死亡,玩家死亡遊戲結束,敵機死亡分數+1。只有玩家可以射擊,且射擊方式固定,通過躲避敵機生存。接下來我們針對這些進行改造,提升遊戲的可玩性和挑戰性。

玩家升級計劃

  1. 玩家初始等級為1,玩家可通過擊殺敵機升級,每擊落30敵機升級一次
  2. 玩家每升級一次,增加一個射擊口
  3. 玩家最多升級兩次

首先用編輯器開啟player/index.js,將等級邏輯加入到玩家的類中。

export default class Player extends Sprite {
  constructor() {
    super(PLAYER_IMG_SRC, PLAYER_WIDTH, PLAYER_HEIGHT)

    // 玩家預設處於螢幕底部居中位置
    this.x = screenWidth / 2 - this.width / 2
    this.y = screenHeight - this.height - 30

    // 用於在手指移動的時候標識手指是否已經在飛機上了
    this.touched = false

    this.bullets = []

    // 初始化事件監聽
    this.initEvent()

    this.playerLevel = 1;
  }

  get level () {
    return this.playerLevel;
  }
  set level (level) {
    this.playerLevel = Math.min(level, 3);
  }

複製程式碼

接下來在main.jsupdate函式加入升級邏輯。

// 其他程式碼...

    update() {
        this.bg.update();

        databus.bullets.concat(databus.enemys).forEach(item => {
            item.update();
        });

        this.enemyGenerate();

        this.player.level = Math.max(1, Math.ceil(databus.score / 30));

        this.collisionDetection();
    }

// 其他程式碼...

複製程式碼

好的,到此玩家已經可以正常升級了。那麼該給予玩家獎勵品了。在player/index.jsshoot函式中我們修改射擊的邏輯。玩家1級時只有中間的射擊口,2級有左邊和中間的射擊口,3級有左中右三個射擊口。

// ...其他程式碼

    /**
     * 玩家射擊操作
     * 射擊時機由外部決定
     */
    shoot() {


      for(let i = 0; i < this.level; i++) {
        const bullet = databus.pool.getItemByClass('bullet', Bullet);
        const middle = this.x + this.width / 2 - bullet.width / 2;
        const x = !i ? middle : (i % 2 === 0 ? middle + 30 : middle - 30);
        bullet.init(
          x,
          this.y - 10,
          10
        )

        databus.bullets.push(bullet)
      }
    }

// ...其他程式碼
複製程式碼

武器的最終形態如圖, 這時候的玩家已經可以為所欲為了<_<,實際上都不需要躲避了。。。:

image

敵人的反擊號角

為了對抗愚昧的玩家,不讓他們為所欲為,最後沒興趣玩下去~~,敵機裝備武器,反擊開始。

首先敵機的子彈是向下,所以複製一份images/bullet.png,並顛倒儲存為images/bullet-down.png, 然後我們重用js/player/bullet.js,在建構函式處增加敵機的子彈配置項,並修改敵人子彈更新邏輯。

const BULLET_IMG_SRC = 'images/bullet.png'
const BULLET_DOWN_IMG_SRC = 'images/bullet-down.png'
const BULLET_WIDTH   = 16
const BULLET_HEIGHT  = 30

const __ = {
    speed: Symbol('speed')
}

let databus = new DataBus()

export default class Bullet extends Sprite {
    constructor({ direction } = { direction: 'up' }) {
        super(direction === 'up' ? BULLET_IMG_SRC : BULLET_DOWN_IMG_SRC, BULLET_WIDTH, BULLET_HEIGHT)
       
        this.direction = direction;

// 其他程式碼...

    // 每一幀更新子彈位置
    update() {
        if (this.direction === 'up') {
            this.y -= this[__.speed] 
            
            // 超出螢幕外回收自身
            if ( this.y < -this.height )
                databus.removeBullets(this)
        } else {
            this.y += this[__.speed]

            // 超出螢幕外回收自身
            if ( this.y > window.innerHeight + this.height )
                databus.removeBullets(this)
        }
    }
}

複製程式碼

接著在js/npc/enemy.js結尾部分為敵人裝備武器, 子彈速度為敵人自身速度+5

import Animation from '../base/animation'
import DataBus   from '../databus'
import Bullet from '../player/bullet';

const ENEMY_IMG_SRC = 'images/enemy.png'
// 其他程式碼...

  update() {
    this.y += this[__.speed]

    // 物件回收
    if ( this.y > window.innerHeight + this.height )
      databus.removeEnemey(this)
  }

  /**
   * 敵機射擊操作
   * 射擊時機由外部決定
   */
  shoot() {
      const bullet = databus.pool.getItemByClass('bullet', Bullet);
      bullet.init(
          this.x + this.width / 2 - bullet.width / 2,
          this.y + 10,
          this[__.speed] + 5
      );

      databus.bullets.push(bullet);
  }
}
複製程式碼

接下來,在js/main.js中加入敵機的射擊邏輯,敵機移動5次、60次時設計。

// 其他程式碼...
 let ctx = canvas.getContext("2d");
 let databus = new DataBus();

const ENEMY_SPEED = 6;
// 其他程式碼...

    /**
     * 隨著幀數變化的敵機生成邏輯
     * 幀數取模定義成生成的頻率
     */
    enemyGenerate(playerLevel) {
        if (databus.frame % 60 === 0) {
            let enemy = databus.pool.getItemByClass("enemy", Enemy);
            enemy.init(ENEMY_SPEED);
            databus.enemys.push(enemy);
        }
    }

// 其他程式碼...

    // 實現遊戲幀迴圈
    loop() {
        databus.frame++;

        this.update();
        this.render();

        if (databus.frame % 20 === 0) {
            this.player.shoot();
            this.music.playShoot();
        }

        databus.enemys.forEach(enemy => {
            const enemyShootPositions = [
                -enemy.height + ENEMY_SPEED * 5,
                -enemy.height + ENEMY_SPEED * 60
            ];
            if (enemyShootPositions.indexOf(enemy.y) !== -1) {
                enemy.shoot();
                this.music.playShoot();
            }
        });

        // 遊戲結束停止幀迴圈
        if (databus.gameOver) {
            this.touchHandler = this.touchEventHandler.bind(this);
          canvas.addEventListener("touchstart", this.touchHandler);
            this.gameinfo.renderGameOver(ctx, databus.score);

            return;
        }

        window.requestAnimationFrame(this.loop.bind(this), canvas);
    }

複製程式碼

這時候我們發現,由於不明宇宙的干擾射線的影響,玩家和敵機的子彈不受控制的亂飛。接下來我們就來恢復世界的秩序吧 ;

經偵測發現是物件池pool的獲取邏輯問題導致子彈不受控問題,我們需要區分獲取玩家、每個敵機的子彈

首先,物件獲取我們加入物件屬性的判斷,當有傳入物件屬性時,我們獲取所有屬性值一致的已回收物件,若沒有找到或者物件池為空時,則用屬性建立新物件

  /**
   * 根據傳入的物件識別符號,查詢物件池
   * 物件池為空建立新的類,否則從物件池中取
   */
  getItemByClass(name, className, properties) {
    let pool = this.getPoolBySign(name)

    if (pool.length === 0) return new className(properties);
   
    if (!properties) return pool.shift();
   
    const index = pool.findIndex(item => {
        return Object.keys(properties).every(property => {
            return item[property] === properties[property];
        });
    });
    return index !== -1 ? pool.splice(index, 1)[0] : new className(properties)
  }

複製程式碼

相應的我們需要給每個子彈設定歸屬,在js/player/bullet.jsBullet類修改constructor

export default class Bullet extends Sprite {
    constructor({ direction, owner } = { direction: 'up' }) {
        super(direction === 'up' ? BULLET_IMG_SRC : BULLET_DOWN_IMG_SRC, BULLET_WIDTH, BULLET_HEIGHT)

        this.direction = direction;

        this.owner = owner;
    }
複製程式碼

接著修改js/player/index.jsshoot,為其中建立的bullets提供歸屬

    /**
     * 玩家射擊操作
     * 射擊時機由外部決定
     */
    shoot() {
      for(let i = 0; i < this.level; i++) {
        const bullet = databus.pool.getItemByClass('bullet', Bullet, { direction: 'up', owner: this });

複製程式碼

同樣處理js/npc/enemy.jsshoot

  /**
   * 敵機射擊操作
   * 射擊時機由外部決定
   */
  shoot() {
      const bullet = databus.pool.getItemByClass('bullet', Bullet, { direction: 'down', owner: this });

複製程式碼

最後處理js/databus.jsremoveBullets的回收邏輯

  /**
   * 回收子彈,進入物件池
   * 此後不進入幀迴圈
   */
  removeBullets(bullet) {
    const index = this.bullets.findIndex(b => b === bullet);

    bullet.visible = false

    this.bullets.splice(index, 1);

    this.pool.recover('bullet', bullet)
  }
}

複製程式碼

這時候敵我的子彈就恢復正常了。不過這時候玩家中彈並不會死亡,現在來讓玩家Go Die吧。在js/main.jscollisionDetection我們判斷增加每一顆子彈如果是敵方的,就判斷其是否打中玩家,是則遊戲結束。玩家的子彈判斷保持不變。

    // 全域性碰撞檢測
    collisionDetection() {
        let that = this;

        databus.bullets.forEach(bullet => {
            for (let i = 0, il = databus.enemys.length; i < il; i++) {
                let enemy = databus.enemys[i];
                if (bullet.owner instanceof Enemy) {
                    databus.gameOver = this.player.isCollideWith(bullet);
                } else if (!enemy.isPlaying && enemy.isCollideWith(bullet)) {
                    enemy.playAnimation();
                    that.music.playExplosion();

                    bullet.visible = false;
                    databus.score += 1;

                    break;
                }
            }
        });

複製程式碼

到此整個簡單改造計劃就結束了,以後還可以新增武器系統,boss戰等等。下面是改造後的遊戲動圖錄屏

demo

本文始發於本人的公眾號:楓之葉。公眾號二維碼

微信小遊戲體驗之打飛機改造計劃

相關文章