简体   繁体   English

为什么jQuery animate()无法使用可变的CSS属性?

[英]Why won't jQuery animate() work with variable css property?

I'm a jQuery/javascript beginner and for fun I'm trying to make a snake game. 我是jQuery / javascript初学者,为了娱乐,我试图做一个蛇游戏。 I think I'm pretty close to getting movement except when I change directions via keyboard arrows, it's not working how I'd expect. 我想我几乎已经开始运动了,除了当我通过键盘箭头更改方向时,它并没有达到我的期望。 For example, the snake will automatically start moving right. 例如,蛇将自动开始向右移动。 If I hit down it will go down BUT still continue to go right. 如果我击倒它会掉下来,但仍然继续正确。 If I hit left, it'll go left but continue to go down. 如果我向左打,它将向左走,但继续下降。

This might be just a fundamental error in my code or something more obvious. 这可能只是我的代码中的一个基本错误或更明显。

JSFiddle: http://jsfiddle.net/zgjg6914/ 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);

The problem is, when you set a new direction, you leave the previous one in aniArgs . 问题是,当您设置新方向时, aniArgs前一个方向保留在aniArgs

Quick fix: in your keydown handler, in all of the if s, you need to reset aniArgs . 快速修复:在keydown处理程序中,在所有if s中,您都需要重置aniArgs

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

I updated your fiddle . 我更新了你的小提琴

I don't think if it's good idea to use time interval to check any behaviour inside game. 我不认为使用时间间隔检查游戏中的任何行为是否是个好主意。 Read sth about preparing games with html5 canvas element (jquery will be also useful there) - imho it's more proper way to create games inside browser 阅读有关使用html5 canvas元素准备游戏的信息(jQuery在那里也将非常有用)-恕我直言,这是在浏览器中创建游戏的更正确方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM