移动帆布盒(不希望的对角线移动)

时间:2015-05-17 00:42:43

标签: javascript canvas

我目前有一个用画布绘制的框,可以使用箭头键 WASD 键向左,向上,向右和向下移动。

问题: 当我按W时,按住A,按下$(function() { var n = 3; var xD = 0; var yD = 0; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); window.addEventListener('resize', resizeCanvas, false); function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; render(); } var ss = { "x": 0, "y": 0, "width": 100, "height": 75 }; function render() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.rect(ss.x, ss.y, ss.width, ss.height); ctx.lineWidth = 1; ctx.strokeStyle = "white"; ctx.stroke(); } function move() { x = ss.x + (xD * n); y = ss.y + (yD * n); ss.x = x; ss.y = y; render(); } $(document).keydown(function(e) { // left xD = e.which == 37 ? -1 : xD; xD = e.which == 65 ? -1 : xD; // up yD = e.which == 38 ? -1 : yD; yD = e.which == 87 ? -1 : yD; // right xD = e.which == 39 ? 1 : xD; xD = e.which == 68 ? 1 : xD; // down yD = e.which == 40 ? 1 : yD; yD = e.which == 83 ? 1 : yD; e.preventDefault(); }); $(document).keyup(function(e) { // left xD = e.which == 37 ? 0 : xD; xD = e.which == 65 ? 0 : xD; // up yD = e.which == 38 ? 0 : yD; yD = e.which == 87 ? 0 : yD; // right xD = e.which == 39 ? 0 : xD; xD = e.which == 68 ? 0 : xD; // down yD = e.which == 40 ? 0 : yD; yD = e.which == 83 ? 0 : yD; e.preventDefault(); }); resizeCanvas(); render(); setInterval(move, .01); });,相关方框将向右上方(对角线)移动。这是一种不希望的效果。 我希望这个“盒子”不能移动对角线。

请解释为什么会发生这种影响,我不明白其背后的逻辑。

我的代码在这里:http://cssdeck.com/labs/collab/stexplorer
在这里:

body {
  margin: 0;
  overflow: hidden;
}

#canvas {
  border: 1px solid #000000;
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
ParseObject.unpinAllInBackground(TaskSummaryHolder.PIN)

1 个答案:

答案 0 :(得分:1)

这背后的逻辑是keydown事件彼此独立激发,因此一次按下多个键将多次触发您的函数,同时更改x和y值。您可以通过创建一个跟踪是否已按下任何键的变量来阻止此操作。例如:

var currentButton = undefined;

$(document).keydown(function(e) {
if(currentButton !== undefined){ 
    return; // there is already a button pressed, don't do logic
}
xD = e.which == 37 ? -1 : xD;
xD = e.which == 65 ? -1 : xD;
// up
yD = e.which == 38 ? -1 : yD;
yD = e.which == 87 ? -1 : yD;
// right
xD = e.which == 39 ? 1 : xD;
xD = e.which == 68 ? 1 : xD;
// down
yD = e.which == 40 ? 1 : yD;
yD = e.which == 83 ? 1 : yD;

currentButton = e.which; // store which key is currently pressed
e.preventDefault();
});

$(document).keyup(function(e) {
if(e.which === currentButton){
     currentButton = undefined; // the button has been released, set to undefined again
}
// left
xD = e.which == 37 ? 0 : xD;
xD = e.which == 65 ? 0 : xD;
// up
yD = e.which == 38 ? 0 : yD;
yD = e.which == 87 ? 0 : yD;
// right
xD = e.which == 39 ? 0 : xD;
xD = e.which == 68 ? 0 : xD;
// down
yD = e.which == 40 ? 0 : yD;
yD = e.which == 83 ? 0 : yD;
e.preventDefault();
});