使用左右箭头键,我应该可以向左右移动头像。 但是,它不能顺利运行,因为它的移动方式如下:按住箭头键时停止 - 停止 - 停止。
看小提琴: https://jsfiddle.net/zk45xgnd/2/
HTML:
<div id='avtr'></div>
的CSS:
#avtr {
position:absolute;
height:50px;
width:50px;
background-color:#f00;
}
jquery的:
var allowedToWalk = false, allowedToWalkTime = true;
var percentage = 1;
var maxWidth = 1000;
$(window).keydown(function(e) {
if(e.which == 39) {
//move to right
allowedToWalk = true;
avatarMoveRight();
}
if(e.which == 37) {
//move to left
allowedToWalk = true;
avatarMoveLeft();
}
}).keyup(function() {
allowedToWalk = false;
});
function avatarMoveRight() {
if(allowedToWalk != false && allowedToWalkTime != false) {
var pos = $("#avtr").css('left');
pos = pos.replace('px', '');
pos = pos - 0;
if((pos - 40) < (percentage * maxWidth)) {
allowedToWalkTime = false;
$("#avtr").animate({left: '+=40'}, 150);
setTimeout(function() {allowedToWalkTime = true;},150);
}
}
}
function avatarMoveLeft() {
if(allowedToWalk != false && allowedToWalkTime != false) {
var pos = $("#avtr").css('left');
pos = pos.replace('px', '');
pos = pos - 0;
if((pos - 4) > 0) {
allowedToWalkTime = false;
$("#avtr").animate({left: '-=40'}, 150);
setTimeout(function() {allowedToWalkTime = true;},150);
}
}
}
如何按住箭头键使其平稳运行?
@adam A的解决方案 https://jsfiddle.net/zk45xgnd/3/
答案 0 :(得分:1)
这是一个更新的代码,具有较低的值和移动之间的等待时间,这使其具有稍微更流畅的动画。但是,我建议查看Phaser的GSAP动画库,了解一些非常先进的东西。
var allowedToWalk = false, allowedToWalkTime = true;
var percentage = 1;
var maxWidth = 1000;
$(window).keydown(function(e) {
if(e.which == 39) {
//move to right
allowedToWalk = true;
avatarMoveRight();
}
if(e.which == 37) {
//move to left
allowedToWalk = true;
avatarMoveLeft();
}
}).keyup(function() {
allowedToWalk = false;
});
function avatarMoveRight() {
if(allowedToWalk != false && allowedToWalkTime != false) {
var pos = $("#avtr").css('left');
pos = pos.replace('px', '');
pos = pos - 0;
if((pos - 40) < (percentage * maxWidth)) {
allowedToWalkTime = false;
$("#avtr").animate({left: '+=5'}, 5);
setTimeout(function() {allowedToWalkTime = true;},5);
}
}
}
function avatarMoveLeft() {
if(allowedToWalk != false && allowedToWalkTime != false) {
var pos = $("#avtr").css('left');
pos = pos.replace('px', '');
pos = pos - 0;
if((pos - 4) > 0) {
allowedToWalkTime = false;
$("#avtr").animate({left: '-=5'}, 5);
setTimeout(function() {allowedToWalkTime = true;},5);
}
}
}