我在javascript中创建一个小游戏,需要同时按下多个键才能进行头像移动。
要识别多个按键,我正在使用“Braden Best”对问题JavaScript multiple keys pressed at once的回答,除了文档似乎没有多任务键盘事件之外,这个问题很有效。例如,如果我想按向上箭头键,然后按向左箭头键,则释放左箭头键,化身将完全停止。
以下是一个示例代码: https://Jsfiddle.net/552gc9dh/1/
var c = document.getElementById("canv");
var canv = c.getContext("2d");
console.log("test");
var map = {};
var playerlist = [];
function player(width, height, x, y, color, speedx, speedy) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.color = color;
this.speedx = speedx;
this.speedy = speedy;
playerlist.push(this);
}
var player1 = new player(50, 50, 0, 0, "red", 2, 2);
console.log(playerlist[0]);
function gravity(playerY) {
}
function createplayerlistener(name, key1, key2, key3, key4) {
onkeydown = onkeyup = function(e) {
e = e || event;
map[e.keyCode] = e.type == 'keydown';
if (name.x + name.speedx < c.width - name.width) {
if (map[key1]) {
name.x += name.speedx;
}
}
if (name.x + name.speedx > 0) {
if (map[key2]) {
name.x -= name.speedx;
}
}
if (name.y + name.speedy < c.height - name.height) {
if (map[key3]) {
name.y += name.speedy;
}
}
if (name.y + name.speedy > 0) {
if (map[key4]) {
name.y -= name.speedy;
}
}
}
}
createplayerlistener(player1, 39, 37, 40, 38);
setInterval(function() {
canv.clearRect(0, 0, c.width, c.height);
for (var i = 0; i <= playerlist.length - 1; i++) {
canv.fillStyle = playerlist[i].color; // iterates through players and draws them
canv.fillRect(playerlist[i].x, playerlist[i].y, playerlist[i].width, playerlist[i].height);
}
}, 10);
答案 0 :(得分:0)
这个答案更像是一种策略......
我会为路线设置变量,并在keyDown
和keyUp
Sudo Code
const North = false;
const West = false;
const South = false;
const East = false;
keyUp = keyDown = (keyType) {
switch(keyType) {
case 'up':
North = !North;
break;
case 'right':
East = !East;
break;
case 'down':
South = !South;
break;
case 'left':
West = !West;
break;
};
}
setInterval({
if(North) //move up
if(South) //move down
if(East) //Move right
if(West) //Move left
}, 10);
这应保持当前的移动,直到您收到取消它的命令。如果用户同时按下它们,它还允许上下或左右相互对抗。
希望这有帮助!
<强>加成强>
可能更高效的选项实际上是在keydown上为特定方向创建setInteval
并在keyUp上删除它,这样如果玩家没有交互你就不会运行额外的周期1/100第二个
directions = {
up: null,
right: null,
down: null,
left: null
}
const startInterval = (keyType) => {
direction[keyType] = setInteval(()=> move(keyType);
}
const endInterval = (keyType) => {
clearInterval( direction[keyType]);
direction[keyType] = null;
}
const keyUp = keyDown = (keyType) {
if(direction[keyType] === null) {
startInteval(keyType);
} else {
endInterval(keyType);
}
}