我是一个 jQuery/javascript 初学者,为了好玩,我正在尝试制作一个贪吃蛇游戏。我认为我已经非常接近移动了,除非我通过键盘箭头改变方向时,它并没有像我期望的那样工作。例如,蛇会自动开始向右移动。如果我击倒它会下降但仍然继续向右走。如果我向左打,它会向左但会继续向下。
这可能只是我的代码中的一个基本错误或更明显的错误。
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);
最佳答案
问题是,当您设置一个新的方向时,您会在 aniArgs
中留下前一个方向。
快速修复:在您的 keydown
处理程序中,在所有 if
中,您需要重置 aniArgs
。
if (e.keyCode == 38) {
aniArgs = {}; // clear previous movement
direction = 'top';
plusOrMinus = '-=25px';
}
我更新了你的 fiddle .
关于javascript - 为什么 jQuery animate() 不能使用变量 css 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28056454/