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