如何在Javascript中对角移动精灵

时间:2016-02-03 05:49:47

标签: javascript character sprite move

角色在每个方向上移动,但是如何按住另一个键以允许它沿对角线方向移动而不是仅停止并向该方向移动?我在这里设置了一个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);

 }

1 个答案:

答案 0 :(得分:0)

现在,我并不是说以下是完美的,但我确实设法让它在一些摆弄之后迅速发挥作用。我已将它发布到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>

祝你好运,我希望至少能让你开始!