从左到右切换时的动画精灵延迟

时间:2018-07-20 01:29:59

标签: javascript animation

我有一个动画效果很好的精灵,但是当您使用箭头键在左右之间切换时,有时会稍有延迟,并且在转弯之前他会停一会儿。

更新:似乎最容易通过左右切换来重新创建,因为它们是瞬间重叠的,两个键同时按下。

是否与清除间隔不正确有关?这是性能瓶颈吗?实例化动画的操作顺序是否错误?

关于为什么的任何想法?

这是页面的代码,只需运行代码段,然后使用左右箭头键使他动起来。

$(document).ready(function() {
  var character = document.getElementById("character");
  var characterPosition = 0;
  var yOffset = 0;
  var runningInterval;
  var isRunning = false;

  function startRun() {
    isRunning = true;
    characterPosition = 0;
    yOffset = 0;
    runningInterval = setInterval(animateRun, 40);
  }

  function animateRun() {
    var newPosition = characterPosition - 200;

    if (newPosition == -1800 && yOffset == 0) {
      newPosition = 0;
      yOffset = -199.33;
    }

    if (newPosition == -1800 && yOffset == -199.33) {
      newPosition = 0;
      yOffset = -398.66;
    }

    if (newPosition == -1200 && yOffset == -398.66) {
      newPosition = 0;
      yOffset = 0;
    }

    character.style.backgroundPosition = newPosition + "px" + " " + yOffset + "px";
    characterPosition = newPosition;
  }

  function stopRun() {
    isRunning = false;
    clearInterval(runningInterval);
  }

  $("body").on("keydown", function(event) {
    // left
    if (!isRunning) {
      if (event.which == 37) {
        $("#character").css("transform", "scaleX(-1)");
        startRun();
      }

      //right
      if (event.which == 39) {
        $("#character").css("transform", "scaleX(1)");
        startRun();
      }
    }
  });

  $("body").on("keyup", function() {
    stopRun();
  });
});
body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#character {
  width: 200px;
  height: 199.33px;
  background-image: url("https://rebootcreate.com/games/testing/assets/braid-run-sprite.png");
  background-repeat: no-repeat;
  background-position: 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Animation Testing</title>
</head>
<body>
  <div id="character"></div>
</body>
</html>

0 个答案:

没有答案