我是一個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);