【问题标题】:Run left / right sprite animation by click单击运行左/右精灵动画
【发布时间】:2012-10-08 05:26:28
【问题描述】:

我对这个精灵动画有疑问。 sprite-sheet 脚本没有改变正确的动画,每次点击同一个方向速度都会加快。

<div id="coordinates">MOUSE XY</div>    
<div id="map" style="width:960px; height:80px; background-color:black; ">   
 <div id="player"></div>  
</div>

Javascript 和 Jquery

<style> #player{background-image:url('girl_60x60.png'); 
    width:60px; height:60px; position:relative; 
    z-index:12; left:465px;}</style>

<script type="text/javascript"> 
 // click event 
 $('#map').click(function(e) { 
  // take coordinates
  var posX = e.pageX ;
  var posY = e.pageY;
  //print X e Y
  $('#coordinates').html("X: " + posX + " Y: " + posY); 

  if (posX <= 480) {   //Check the click relative to the center.
   setInterval('ani_left()',100); //left animation                          
  } else {              
   setInterval('ani_right()',100); //right animation
  }
}); 

var frame = 1;

// Right animation
function ani_right() {
 var left = 60 * frame;  //next frame every 60px
 var top = 0;
 $('#player').css('backgroundPosition','-'+left+'px -'+top+'px');
 frame++;
}
// left animation
function ani_left() {
 var left = 60 * frame;
 var top = 60;   //second row of frames
 $('#player').css('backgroundPosition','-'+left+'px -'+top+'px');
 frame++;
}
</script>

【问题讨论】:

    标签: javascript jquery sprite-sheet


    【解决方案1】:

    您应该使用clearInterval(idInterval) 停止执行先前的setInterval

    我建议您使用setInterval(funcName,100) 而不是setInterval('funcName()',100)

    var idInt = -1; // add this
     // click event 
     $('#map').click(function(e) { 
         if(idInt != -1) 
             clearInterval(idInt); // add this 
    /* .. CUT .. */
    
      if (posX <= 480) {   //Check the click relative to the center.
          idInt = setInterval(ani_left,100); //left animation                          
      } else {              
          idInt = setInterval(ani_right,100); //right animation
      }
    }); 
    
    /* cut */
    

    Fiddle here

    【讨论】:

      【解决方案2】:

      在开始新的抽奖间隔之前,您必须清除旧抽签间隔

      var interval;
      
      if (posX <= 480) {   //Check the click relative to the center.
         clearInterval(interval);
         interval = 0;
         interval = setInterval(ani_left,100); //left animation                          
        } else {              
         clearInterval(interval);
         interval = 0;
         interval = setInterval(ani_right,100); //right animation
        }
      

      【讨论】:

      • 请注意,您在那里使用相同的间隔,如果该代码按原样粘贴到他的代码中,则每次用户单击时都会创建整数并且不会被清除。
      • 你真的告诉 ani_right 或 left 他们应该画什么精灵...我没有看到这样做的代码
      • 你有没有偶然在一个 url 上有这个设置来看看?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2018-06-11
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多