[英]Smoother movement or diagonal movement - Javascript
我正在嘗試使我的<div>
更加平滑或對角移動。 當按下W
和D
類的兩個鍵時,它只會向一個方向移動。 我想使其傾斜移動。 有沒有一種方法可以使機芯不那么動盪。 divShootingGallery
是父<div>
或游戲板,而divShooter
是一個臨時框。 我只想使用JavaScript,而不要使用jQuery。
這是我的代碼:
function keyClick(){ var divShooter = document.getElementById("divShooter"); var divGameBoard = document.getElementById("divShootingGallery"); switch(event.keyCode) { case 65://a to move left if(divShooter.offsetLeft > 0){ //checks to make sure the left side of the shooter is not off the left side divShooter.style.left = divShooter.offsetLeft - 10 + "px"; }else{ divShooter.style.left = "0px"; } break; case 68://d to move right if(divShooter.offsetLeft + divShooter.clientWidth < divGameBoard.clientWidth){ //checks to make sure the right side of the shooter is not off the right side divShooter.style.left = divShooter.offsetLeft + 10 + "px"; } else{ divShooter.style.left = (divGameBoard.clientWidth - divShooter.clientWidth) + "px"; } break; case 87://w key up for right player divShooter.style.top = divShooter.offsetTop - 10 + "px"; if(divShooter.offsetTop <= 0){ divShooter.style.top = "0"; } break; case 83://s key down for right player divShooter.style.top = divShooter.offsetTop + 10 + "px"; if(divShooter.offsetTop + divShooter.clientHeight >= divGameBoard.clientHeight){ divShooter.style.top = divGameBoard.clientHeight - divShooter.clientHeight + "px"; } break; } } window.addEventListener('keydown',keyClick,true);
html,body{ height:100%; width:100%; } #divShootingGallery{ position:absolute; left:0; right:0; margin:auto; width:1000px; height:600px; background:bisque; } #divShooter{ position:absolute; left:475px; bottom:0; width:50px; height:50px; background:blue; }
<head> <link rel="stylesheet" href="style.css" type="text/css"/> <script type="text/javascript" src="script.js"></script> </head> <body> <div id="divShootingGallery"> <div id="divShooter"></div> </div> </body>
順便說一句,您的keyClick()函數中缺少“事件”
function ketClick(event) {
...
}
請檢查此線程,您的問題非常相似: 使用socket.io在javascript中播放播放器
基本上,您必須實現keydown和keyup事件,並記下當前按下了哪些鍵。 然后,您應該在模擬循環中使用該信息,以便正確移動對象。 模擬循環可以是這樣的計時器:
function moveObject() {
... check which keys are down and move accordingly ...
}
setInterval(function() {
moveObject();
}, 100);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.