如何在 JavaScript 中沿对角线移动精灵?

How can I move sprite diagonally in JavaScript?

角色向各个方向移动,但我怎样才能按住另一个键让它沿对角线移动而不是停止并沿那个方向移动?我在这里设置了一个gif:https://i.gyazo.com/1a13d207f94e4361ab8e015679ba5d85.gif

JavaScript:

$(document).ready(function(){
        
       $("#character").addClass("front-stand");
        
    });
    
        //setInterval(moveChar, 20);
   
    var keypressed = 0;
    
    
    $(document).keydown(function(e){
        
        if (!keypressed){
            
            keypressed = e.keyCode;
            moveChar();
           
            
            if (e.keyCode == keypressed){
                keypressed = false;
                $("#character").stop(false,true);
            }
            
            
            function moveChar(){
        
            switch (e.keyCode){
                    
                case 38:
                    $("#character").animate({top: "-=25"}, 200);
                break;
                    
                case 39:
                    $("#character").animate({left: "+=25"}, 200);
                break;
                    
                case 40:
                    $("#character").animate({top: "+=25"}, 200);
                break;
                    
                case 37:
                    $("#character").animate({left: "-=25"}, 200);
                break;    
    
           }
        
        
    }
            
            
        }
        
    });


#character{
    position: absolute;
    top: 0;
    left: 0;
    height: 32px;
    width: 32px;
    background-image:url(character.png);
    
 }

现在,我并不是说以下内容是完美的,但我确实设法让它在一些摆弄之后快速运行。我已经将它发布到 codepen,所以你应该可以随时看到它,但我也把它放在这里以防万一。很可能有一种更干净、更好的方法来做到这一点,但到目前为止,这就是我所拥有的。

我注意到的一些随机错误

如果您同时按下两个键,它会先注册 1 个动画的侧向运动,然后再为这两个运动设置动画。您可能可以通过调用延迟 100 毫秒来解决这个问题,但我没有机会测试它是如何做到的。

CodePen Link

function _animate(el, key) {
  if (key < 37 || key > 40) return undefined;
  el = $(el);
  var styles = {};
  if (el.data('animations') == undefined)
    el.data('animations', []);
  var data = el.data('animations');
  if (data.indexOf(key) == -1)
    data.push(key);
  el.data('animations', data); //Push the object to the element.
  for (var i = 0; i < data.length; i++) {
    var k = data[i]
    switch (k) {
      case 37:
        styles.left = '-=25px';
        break;
      case 38:
        styles.top = '-=25px';
        break;
      case 39:
        styles.left = '+=25px';
        break;
      case 40:
        styles.top = '+=25px';
        break;
    }
  }

  console.log(styles);
  el.animate(styles);

}
$(document).on('keydown', function(e) {
  _animate($('#sprite'), e.keyCode);
}).on('keyup', function(e) {
  data = $('#sprite').data('animations');
  data.splice(data.indexOf(e.keyCode), 1);
  $('#sprite').clearQueue();
});
div#sprite {
  background-color: green;
  position: relative;
  height: 25px;
  width: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sprite">&nbsp;</div>