游戏中的javascript精灵动画

游戏中的javascript精灵动画,javascript,html,animation,sprite,Javascript,Html,Animation,Sprite,我正在一个小Javascript游戏中制作一个精灵的简单动画,一只蚊子在向右飞行时改变状态。这些状态对应于我的平铺表中的两个不同图像 到目前为止,我一直在这样做,但动画非常不规则: for (var i = 0; i < mosquitos.length; i++) { var mosquito = mosquitos[i]; setInterval (updateAnimation, 500); mosquito.update(); // rest of code n

我正在一个小Javascript游戏中制作一个精灵的简单动画,一只蚊子在向右飞行时改变状态。这些状态对应于我的平铺表中的两个不同图像

到目前为止,我一直在这样做,但动画非常不规则:

for (var i = 0; i < mosquitos.length; i++) {
  var mosquito = mosquitos[i];

  setInterval (updateAnimation, 500);
  mosquito.update();

  // rest of code non-relevant to animation here...
这两个州当然是FLYINGRIGHT和FLYINGRIGHT1。。。 问题是蚊子开始很快很不规则地活动。我希望它改变状态,即每半秒。我尝试了不同的时间段,但效果总是一样的

如果我缺少的东西不是那么明显的话,我可以把整件事都说出来

感谢您的帮助和见解

以下是我网站上的游戏:


我认为你应该重新考虑这一部分:

var mosquito = mosquitos[i];
setInterval (updateAnimation, 500);
我想你希望每个新的“更新动画”都有不同的蚊子(蚊子[0],蚊子[1]…蚊子[I])。但真正发生的是不同的事情。每次你得到同样的蚊子(蚊子[i])。 这是因为setInterval()函数的异步行为

function updateAnimation () {
  next();

  function next() {
           // every time, mosquito is equal to mosquitos[i]
           // and NOT mosquitos[0], then mosquitos[1] ...
           mosquito.state = mosquito.FLYINGRIGHT1;
           setTimeout (previous, 500);

          function previous()
                  {
                       mosquito.state = mosquito.FLYINGRIGHT;

                  }

      }
   }

我认为一把小提琴会很有帮助:)问题是整个东西有很多资源可以上传,声音等等。。。我将制作一个简化版,专注于动画,但这并不容易。您好,我上传了游戏,并在原始问题中添加了链接。一定要让我知道你的想法…嘿,我看了一下。它在Chrome中看起来不太糟糕。您是否已针对您的问题进行了更改?或者,它是特定于某个浏览器的吗?您好,我可以用以下方法实现一些随机蚊子动画:在LoadHandler函数中:setInterval(updateAnimation,300);在playGame()函数中:findWaitTime=function(){waitTime=Math.ceil(Math.random()*6);}updateAnimation=function(){findWaitTime();if(waitTime>3){Discene.state=Discene.FLYINGRIGHT;}else{Discene.state=Discene.FLYINGRIGHT1;}这是随机的,但不是那么糟糕。你觉得呢?现在只有一只蚊子。。。我认为问题在于setInterval和setTimeout的行为和交互方式……如果使用不当,会造成混乱。。。也许有一个优雅而简单的解决方案,但现在我错过了。我在原始问题中添加了一个与实际游戏的链接,供您考虑。谢谢
function updateAnimation () {
  next();

  function next() {
           // every time, mosquito is equal to mosquitos[i]
           // and NOT mosquitos[0], then mosquitos[1] ...
           mosquito.state = mosquito.FLYINGRIGHT1;
           setTimeout (previous, 500);

          function previous()
                  {
                       mosquito.state = mosquito.FLYINGRIGHT;

                  }

      }
   }