-1

我对这个精灵动画有问题。 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>
4

2 回答 2

1

您应该停止执行以前setInterval的 with clearInterval(idInterval)

我建议你使用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 */

在这里提琴

于 2013-08-28T08:04:37.913 回答
0

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

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
  }
于 2012-10-17T20:49:05.530 回答