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

微信小遊戲推出已有幾天了,這個功能對小程序和小遊戲的推進影響不用多說,你們趕忙摩拳擦掌往上擼就能夠了。關於如何開發官方文檔已經說明了,這篇則是對官方的打飛機demo一些小改造。json

開發預備式

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

打飛機小遊戲

使用無AppID模式建立一個微信小遊戲後能夠看到官方demo,其中入口文件和配置文件:game.jsgame.jsongame.js引入並初始化包含整個打飛機的遊戲場景、參與者(玩家飛機和敵方飛機)、遊戲邏輯的主函數的main.js。在main.js中咱們能夠發現因爲Adapter的存在,這裏的代碼和咱們日常的代碼寫法沒什麼差別了。遊戲的主邏輯以下圖:canvas

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)
      }
    }

// ...其餘代碼

武器的最終形態如圖, 這時候的玩家已經能夠隨心所欲了<_<,實際上都不須要躲避了。。。:ide

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結尾部分爲敵人裝備武器, 子彈速度爲敵人自身速度+5oop

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戰等等。下面是改造後的遊戲動圖錄屏

圖片描述

本文始發於本人的公衆號:楓之葉。公衆號二維碼
圖片描述

相關文章
相關標籤/搜索