2012-10-17 5 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> 

자바 스크립트와 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