2012-10-17 61 views
-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> 

回答

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

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 
    } 
+1

要小心,你使用相同的時間間隔出現,如果代碼粘貼到自己的代碼是,整數會在每次用戶點擊創建,將無法清關。 – hobberwickey

+0

問題仍然存在,即使clearInterval(間隔) – Micky

+0

你實際上告訴ani_right或離開他們應該繪製什麼樣的雪碧......我沒有看到代碼這樣做 – Mutmatt