【发布时间】:2014-12-18 11:20:36
【问题描述】:
我正在尝试做两件事但找不到方法:
- 更重要的是——让船在键向上时完全停止之前朝
keydown的方向多一点动画,如果我按另一个方向,船将等待动画完成,然后再改变方向。
2.使飞船运动更逼真,不像文本编辑器。
$(document).ready(function() {
//Variables
var screenWidth = $(window).width(); //Screen width
var screenHeight = $(window).height(); //Screen height
var shipWidth = $("#ship").width(); //Ship width
var y = 0; //Background y position
var currentShipPos; //ship current position
setShipPosition(screenWidth / 2 - shipWidth / 2, screenHeight / 1.5 - shipWidth / 2);
startBackgroundMovement();
//Start move the screen
function startBackgroundMovement() {
setInterval(function() {
y += 1;
$('body').css('background-position-y', y + 'px');
}, 10);
}
//Spaceship starting position
function setShipPosition(posX, posY) {
$("#ship").css("left", posX);
$("#ship").css("top", posY);
currentShipPos = posX;
//alert(currentShipPos);
}
//Move spaceship
$(document).keydown(function(e) {
if (!$('#ship').is(':animated')) {
switch (e.which) {
case 37: //left
currentShipPos -= 10;
$('#ship').animate({
left: currentShipPos + "px"
}, 0, 'swing');
//left edge of screen
if (currentShipPos < 0) {
currentShipPos = 0;
}
break;
case 39: //right
currentShipPos += 10;
$('#ship').animate({
left: currentShipPos + "px"
}, 0, 'swing');
//right edge of screen
if (currentShipPos > screenWidth - shipWidth) {
currentShipPos = screenWidth - shipWidth;
}
break;
default:
return;
}
e.preventDefault(); //not sure if needed
}
});
});
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
body {
background-image: url('http://www.playmycode.com/dynamic/project_images/495/3495/20888.1363023335.png');
background-repeat: repeat;
overflow: hidden;
background-position: 0 0;
}
#ship {
position: absolute;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<img id="ship" src="http://www.clipartbest.com/cliparts/dTr/M8g/dTrM8gnT9.png" width="40px" />
</body>
【问题讨论】:
-
问题是你没有宇宙飞船的动画循环,所以键事件以键盘发送它们的速率出现。你应该有一个循环并在那里检查是否按下了键
标签: jquery jquery-animate settimeout setinterval keydown