2015-05-14 61 views
1

我想使用JavaScript/jQuery制作太空入侵者游戏。现在我的问题是我无法让飞船在屏幕上平稳移动。平滑和快速的精灵动画(CSS)

我正在使用​​事件来更改sprite的CSS位置n像素。当我给它一个很高的价值时,精灵移动得很快但并不顺利。当我选择将精灵移动1px时,看起来更平滑,但速度很慢。任何想法如何处理它?

The live demo is here。使用WSAD键移动精灵。

PS我不是问动画库。我只想用JavaScript/jQuery来实现它。

$(document).ready(function() { 
    var xPos, yPos; 

    var height = $(document).height(); 
    var width = $(document).width(); 

    function move(dir) { 
      console.log(height + "," + width); 
    xPos = parseInt($('#sprite').css('left')); 
    yPos = parseInt($('#sprite').css('top')); 

    switch (dir) { 
     case 'up': 
     if (yPos > 10) { $('#sprite').css('top', yPos - 10 + "px"); } 
     break; 
     case 'down': 
     if (yPos < height-140) { $('#sprite').css('top', yPos + 10 + "px"); } 
     break; 
     case 'left': 
     if (xPos > 10) { $('#sprite').css('left', xPos - 10 + "px"); } 
     break; 
     case 'right': 
     if (xPos < width-140) { $('#sprite').css('left', xPos + 10 + "px"); } 
     break; 
    } 
    } 

    $(document).keydown(function(event) { 
     var mykey = String.fromCharCode(event.which);   
     if (mykey == "W" || mykey == "w") { move('up'); } 
     if (mykey == "S" || mykey == "s") { move('down') } 
     if (mykey == "A" || mykey == "a") { move('left') } 
     if (mykey == "D" || mykey == "d") { move('right') }   
    }); 

}); 
+1

这似乎是一个完美的用例帆布 – fcalderan

+1

你应该真的考虑使用一些html5游戏引擎(crafty.js)。你采取的方式只会让你陷入痛苦和痛苦的世界。 如果你不想考虑使用引擎,那么你应该做一些缓解,即开始移动1px的值,只要你持有一些关键逐渐增加运动的速度,可以说,10px(这应该最大)每个时间间隔。那么你需要一些摩擦来平稳停止。最后,如果你可以实现对角线运动,那将会很好。 – Drops

回答

2

只需添加CSS3 transition你的船:

#sprite{ 
    -webkit-transition : all 0.4s ease-in-out; 
    -moz-transition : all 0.4s ease-in-out; 
    -o-transition : all 0.4s ease-in-out; 
    transition : all 0.4s ease-in-out; 
} 

然而,animating with translate is better than position top/left(由保罗·爱尔兰的文章)。

此外,通过缓存$('#sprite')

var $sprite = $('#sprite'); 

function move(dir) { 
    xPos = parseInt($sprite.css('left')); 
    yPos = parseInt($sprite.css('top')); 
    ... 

优化代码如果你不这样做(如代码是目前),你强迫jQuery来走遍整个DOM很多次,每次一个键被按下。如果你这样做,这艘船就会被缓存起来,所以jQuery不必每次都查找它。我建议你看看jQache以便轻松缓存。