21天徒手擼一個遊戲引擎(3)敵人,敵人

如何設置敵人canvas

在game.js中設置一個變量:數組

let time = 0

在 step中,讓time自增:app

time += 1;

時間間隔就是:dom

if (time % 150 == 0) {
    //這裏增長敵人
}

因爲敵人不少,所以是一個數組:spa

const enemys = []

敵人的圖片要加到資源載入器中:code

loader.add('enemy', 'images/enemy.png')

當間隔必定時間時,增長敵人:圖片

time += 1;
if (time % 150 == 0) {
    const enemy = new Sprite(0, 0, res['enemy'], 0.5)
    enemy.setPosition(rand(0, windowWidth), 0)
    enemys.push(enemy)
}

繪製敵人資源

enemys.map(enemy => {
    enemy.y++;
    enemy.draw(context)
})

隨機數,讓敵人水平x位置是0~屏幕寬度:get

function rand(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

如今,效果以下:it

image

如今,game.js 所有代碼以下:

import './libs/weapp-adapter'
import './libs/symbol'
import {
  ResLoader,
  Sprite
} from './codetyphon/index'
const context = canvas.getContext('2d')
const {
  windowWidth,
  windowHeight
} = wx.getSystemInfoSync()

let time = 0
const enemys = []

function rand(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}
const loader = new ResLoader()
loader.add('player', 'images/player.png')
loader.add('enemy', 'images/enemy.png')
loader.on_load_finish((res) => {
  const player = new Sprite(0, 0, res['player'], 0.5)
  player.setPosition(windowWidth / 2, windowHeight - player.height)
  const step = (timestamp) => {
    time += 1;
    if (time % 150 == 0) {
      const enemy = new Sprite(0, 0, res['enemy'], 0.5)
      enemy.setPosition(rand(0, windowWidth), 0)
      enemys.push(enemy)
    }
    context.clearRect(0, 0, windowWidth, windowHeight)
    player.update()
    player.draw(context)
    enemys.map(enemy => {
      enemy.y++;
      enemy.draw(context)
    })
    window.requestAnimationFrame(step);
  }
  window.requestAnimationFrame(step);
  wx.onTouchMove(function (res) {
    const x = res.changedTouches[0].clientX
    const y = res.changedTouches[0].clientY
    player.setPosition(x, y)
  })
})

下一篇,是增長碰撞檢測。

相關文章
相關標籤/搜索