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