2015-01-20 41 views
1

我是一個jQuery/JavaScript初學者,爲了好玩,我試圖做一個蛇遊戲。除了當我通過鍵盤箭頭改變方向時,我覺得我非常接近移動,這不符合我的期望。例如,蛇會自動開始向右移動。如果我擊倒,它會下降,但仍然繼續向右。如果我左擊,它會離開,但繼續下去。jQuery animate()爲什麼不能使用變量css屬性?

這可能只是我的代碼中的一個基本錯誤或更明顯的東西。

的jsfiddle:http://jsfiddle.net/zgjg6914/

var direction = 'left'; 
var plusOrMinus = '+=25px'; 

// create the object literal 
var aniArgs = {}; 

function myFunction(){ 
    aniArgs[direction] = plusOrMinus; 
    var posTop = $('.snake_bit').position().top + 25; 
    var posLeft = $('.snake_bit').position().left + 25; 
    if (posTop > 500 || posLeft > 500 || posTop < 25 || posLeft < 25) { 
     gameOver(); 
     return; 
    } 
    $('.snake_bit').animate(aniArgs, 0); 
    console.log('top: ' + posTop + ' left: ' + posLeft); 
} 
function gameOver(){ 
    clearInterval(theInterval); 
    console.log('game over'); 
} 

$(document).keydown(function(e){ 
    if (e.keyCode == 38) { 
     direction = 'top'; 
     plusOrMinus = '-=25px'; 
    } else if (e.keyCode == 40) { 
     direction = 'top'; 
     plusOrMinus = '+=25px'; 
    } else if (e.keyCode == 37) { 
     direction = 'left'; 
     plusOrMinus = '-=25px'; 
    } else if (e.keyCode == 39) { 
     plusOrMinus = '+=25px'; 
     direction = 'left'; 
    } 
}); 

var theInterval = setInterval(myFunction, 1000); 

回答

0

我不認爲如果它的使用時間間隔來檢查遊戲內的任何行爲好主意。閱讀有關準備遊戲with html5 canvas element(jquery也將在那裏有用) - imho它是更合適的方式來創建內部瀏覽器遊戲

2

問題是,當你設置一個新的方向,你離開前一個aniArgs

快速修復:在您的​​處理程序中,在所有if s中,您需要重置aniArgs

if (e.keyCode == 38) { 
    aniArgs = {}; // clear previous movement 
    direction = 'top'; 
    plusOrMinus = '-=25px'; 
} 

我更新了fiddle

相關問題