如何设置敌人
在 game.js 中设置一个变量:
let time = 0
在 step 中,让 time 自增:
time += 1;
工夫距离就是:
if (time % 150 == 0) {// 这里减少敌人}
因为敌人很多,因而是一个数组:
const enemys = []
敌人的图片要加到资源载入器中:
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~ 屏幕宽度:
function rand(min, max) {return Math.round(Math.random() * (max - min) + min);
}
当初,成果如下:
当初,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)
})
})
下一篇,是减少碰撞检测。