如何设置敌人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
如今,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) }) })
下一篇,是增长碰撞检测。