(2). 通过方向键控制移动,按下空格射出子弹。

首先需要有一个全局函数,能够监听用户的按键值,其实就是onmousedown啦。



// 全局监听按键触发对应操作
document.onkeydown = (e) => {
const target = Number(e.which)
switch (target) {
case 37:
roleAction('left')
break
case 38:
roleAction('up')
break
case 39:
roleAction('right')
break
case 40:
roleAction('bottom')
break
case 32:
roleAction('shot')
break
}
}


监听到对应的值触发roleAction函数,同时更新角色当前方向。



// 任务的动作更新对应数据
const roleAction = (action: string) => {
// 获取任务坐标,执行对应行为
// const people: any = document.getElementById('role')
switch (action) {
case 'up':
role.direction = 'up'
drawRole(role.x, role.y -= role.step)
// people.style.top = Number(people.style.top.slice(0, -2)) - 10 + 'px'
break
case 'right':
role.direction = 'right'
drawRole(role.x += role.step, role.y)
// people.style.left = Number(people.style.left.slice(0, -2)) + 10 + 'px'
break
case 'bottom':
role.direction = 'bottom'
drawRole(role.x, role.y += role.step)
// people.style.top = Number(people.style.top.slice(0, -2)) + 10 + 'px'
break
case 'left':
role.direction = 'left'
drawRole(role.x -= role.step, role.y)
break
case 'shot':
// const am = new Ammunition(role.x + 10, role.y - 10, 6, 4, role.diretion)
const am = new Ammunition(getAmmunPix().cx,getAmmunPix().cy, 6, 4, role.direction)
ammuniResp.push(am)
drawShot()
}
}


drawRole函数首先会做一个边界检测,符合规则就更新role的位置信息,并重绘。