如何将键盘功能更改为屏幕操纵杆?我正在构建一个 html5 游戏,我完全迷失了如何添加操纵杆。
下面是需要一些帮助的代码。非常感谢你:)
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
enemy = new Image();
enemy.src = '8bit_enemy.png';
ship = new Image();
ship.src = 'ship.png';
starfield = new Image();
starfield.src = 'starfield.jpg';
document.addEventListener('keydown', keyDown, false);
document.addEventListener('keyup', keyUp, false);
canvas.addEventListener('click', gameStart, false);
gameLoop();
}
function gameStart() {
gameStarted = true;
canvas.removeEventListener('click', gameStart, false);
}
//The main function of the game, it calls all the other functions needed to make the game run
function gameLoop() {
clearCanvas();
drawStarfield()
if (alive && gameStarted && lives > 0) {
hitTest();
shipCollision();
moveLaser();
moveEnemies();
drawEnemies();
drawShip();
drawLaser();
}
scoreTotal();
game = setTimeout(gameLoop, 1000 / 30);
}
//Checks to see which key has been pressed and either to move the ship or fire a laser
function keyDown(e) {
if (e.keyCode == 39) rightKey = true;
else if (e.keyCode == 37) leftKey = true;
if (e.keyCode == 38) upKey = true;
else if (e.keyCode == 40) downKey = true;
if (e.keyCode == 88 && lasers.length <= laserTotal) lasers.push([ship_x + 25, ship_y - 20, 4, 20]);
}
//Checks to see if a pressed key has been released and stops the ships movement if it has
function keyUp(e) {
if (e.keyCode == 39) rightKey = false;
else if (e.keyCode == 37) leftKey = false;
if (e.keyCode == 38) upKey = false;
else if (e.keyCode == 40) downKey = false;
}
window.onload = init;