我正在尝试使用javascript,html和css制作一些2D游戏。
这只是一个开始,但似乎我有一些奇怪的问题。
当我向上移动时,我向上移动我的播放器块并向上滚动但滚动顶部滚动更多然后移动播放器块。
我正在获得玩家阻止位置,以50px向上移动并记录scrollTop位置以通过订阅向上移动相同的50px。
$(document).ready(function() {
//map info
var $map = $('#map'),
viewportWidth = +$(window).width(),
viewportHeight = +$(window).height(),
mapWidth = +$map.width(),
mapHeight = +$map.width();
//player info
var $player = $('.player').eq(0);
//Adding some logic
//Half height and width of map and half of viewport to center it
var halfMW = mapWidth / 2,
halfMH = mapHeight / 2,
halfVW = viewportWidth / 2,
halfVH = viewportHeight / 2;
//Now we need to get subsrtiction of half map width and half viewport width
//and same for height
var mapPositionX = halfMW - halfVW,
mapPositionY = halfMH - halfVH;
//Now we need to put map in negative values so the viewport stands in the center
//Css example
/*
$map.css({
'top': '-' + mapPositionY + 'px',
'left': '-' + mapPositionX + 'px'
});
*/
//Scroll example
$(document).scrollLeft(mapPositionX);
$(document).scrollTop(mapPositionY);
//moving player
$(document).keydown( function(key) {
console.log(key.which);
//down - 40
//right - 39
//up - 38
//left - 37
if(key.which === 38) {
var posUP = +$player.css("top").replace("px", "");
$player.css('top', posUP-50+'px');
$(document).scrollTop($(document).scrollTop() - 50);
}
});
});

html, body {
margin: 0;
padding: 0;
}
#map {
width: 10000px;
height: 10000px;
background: #71D014;
position: relative;
overflow: scroll;
}
.blocks {
width: 100px;
height: 100px;
position: absolute;
top: 4950px;
left: 4950px;
background: orange;
}
.player {
width: 50px;
height: 50px;
position: absolute;
top: 5050px;
left: 5050px;
background: #005ED2;
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tanks</title>
<link rel="stylesheet" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="map">
<div class="blocks"></div>
<div class="player"></div>
</div>
<script src="js/main.js"></script>
</body>
</html>
&#13;
答案 0 :(得分:0)
我发现了什么问题。
键盘上的 向上,向下,向左和向右箭头 被设置为移动scroll x and y
的默认值,我只需要添加preventDefault();
在开始。