如何将键盘功能更改为屏幕操纵杆? 我正在构建一个html5游戏,我完全迷失了如何添加操纵杆。 p>
以下是需要一些帮助的代码。非常感谢您提前:))
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;
答案 0 :(得分:1)
你需要这样的东西:
function doKeyDown(e){
//====================
// THE W KEY
//====================
if (e.keyCode == 87) {
clearCanvas();
y = y - 10;
canvas_context.fillRect(x, y, 50, 30);
}
//====================
// THE S KEY
//====================
if (e.keyCode == 83) {
clearCanvas();
y = y + 10;
canvas_context.fillRect(x, y, 50, 30);
}
//====================
// THE A KEY
//====================
if (e.keyCode == 65) {
clearCanvas();
x = x - 10;
canvas_context.fillRect(x, y, 50, 30);
}
//====================
// THE D KEY
//====================
if (e.keyCode == 68) {
clearCanvas();
x = x + 10;
canvas_context.fillRect(x, y, 50, 30);
}
}
function clearCanvas() {
canvas.width = canvas.width;
}