[英]JQuery animate top and left same time (jumping & running)
我正在尝试创建一个非常简单的2D游戏,在该游戏中,您会自动向前奔跑,然后在按下按键时跳开,以避免在前进过程中遇到障碍。
到目前为止,我做到了。 唯一的问题是跳跃“停止”了向前运动。 例如,如果您按住向上按钮,它将停止整个游戏,并且您会像鸟一样继续向上飞行...
谁能给我一些如何解决的建议? 如果有人可以指导我如何在赛道上放置1-2个随机障碍物并重新开始游戏,并且如果这些障碍物被用户击中,它还显示出行进的总位置,我也会喜欢它。
我的计划是每次完成课程后都加快游戏速度!
在此先感谢:)
<div style='' id='map'></div>
$(function(){
var unjump = function(){
$('#player').stop().animate({
bottom: '33'
});
}
var jump = function(){
$('#player').stop().animate({
bottom: '+=100'
});
setTimeout(unjump, 1000);
}
$(document).keydown(function(e) {
switch(e.which) {
case 38: // up
jump();
break;
}
});
var player = '<div id="player"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
if (position.left > width){
$("#player").css( "left", 0 );
}
$('#player').stop().animate({
left: '+=200'
});
}
run = setInterval(run, 100);
});
主要错误在于播放器的css定位
CSS代码
#player{
width:10px;
height:10px;
border:solid;
position:absolute;
bottom:0px;
}
#map{
position:relative;
}
HTML代码
<div style='border:solid ;height:100px' id='map'></div>
js代码
var interval = null;
var interval2 = null;
$(function () {
var player = '<div id="player"></div>';
$("#map").append(player);
var unjump = function () {
$('#player').stop().animate({
bottom: '0'
});
};
var jump = function () {
$('#player').stop().animate({
bottom: '+=100'
}, 500);
interval2 = setTimeout(unjump, 500);
};
$(document).keydown(function (e) {
switch (e.which) {
case 38: // up
jump();
break;
}
});
function run() {
var width = $('#map').width();
if ($('#player').position().left > width) {
$("#player").css("left", 0);
}
$('#player').stop().animate({
left: '+=10'
});
}
interval = setInterval(run, 500);
});
试试这个: https : //fiddle.jshell.net/u8deLxkz/2/
主要问题是仅在没有其他动画正在运行时才执行运行动画。 除此之外,我整理了一下代码。
$(function(){
//No need for two separate functions, left is handled here as well
function jump(){
$('#player').animate({
bottom: '+=30',
left: '+=10'
},100).animate({
bottom: '-=30',
left: '+=10'
},100);
}
//I think keyup gives better results
$(document).keyup(function(e) {
switch(e.which) {
case 38: //up
jump();
break;
}
});
var player = '<div id="player" style="width: 50px; height: 50px; background-color: blue; position:absolute; bottom:500px;"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
$('#player').position()
console.log('pos ' + position.left + "\nwidth: " + width);
if (position.left > width){
$("#player").finish();
$("#player").css( "left", 0 );
}
//Continue with horizontal animation only if jumping is not in progress
if(!$('#player').is(':animated') ){
$('#player').animate({
left: '+=10'
},100);
}
}
var go = setInterval(run, 100);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.