我正在开发一个基于Asteroids的小游戏,只使用DOM而非Canvas。目前,当按下箭头键时,“飞船”移动得相当平滑,但是我该如何给予飞船动量呢?当用户松开键时,我不希望飞船停止。我试图模拟一点太空物理学。如何让这艘飞船在保持原来方向运动的同时允许自由旋转,而不会朝着它当前指向的方向移动(除非按下上箭头)?有什么想法吗?
var Keys = {
up: false,
down: false,
left: false,
right: false
}
window.onkeydown = function( e ) {
var kc = e.keyCode;
e.preventDefault();
if ( kc === 37 ) Keys.left = true;
else if ( kc === 38 ) Keys.up = true;
else if ( kc === 39 ) Keys.right = true;
else if ( kc === 40 ) Keys.down = true;
};
window.onkeyup = function( e ) {
var kc = e.keyCode;
e.preventDefault();
if ( kc === 37 ) Keys.left = false;
else if ( kc === 38 ) Keys.up = false;
else if ( kc === 39 ) Keys.right = false;
else if ( kc === 40 ) Keys.down = false;
};
@import url( "https://fonts.googleapis.com/css?family=Nunito" );
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
font-family: "Nunito", sans-serif;
font-size: 4rem;
}
b {
display: block;
transform: rotate( 180deg );
}
<div>
<b>v</b>
</div>
<script>
function update() {
if ( Keys.up ) {
document.querySelector( 'div' ).style.transform += 'translateY( -1px )';
}
else if ( Keys.down ) {
document.querySelector( 'div' ).style.transform += 'translateY( 1px )';
}
if ( Keys.left ) {
document.querySelector( 'div' ).style.transform += 'rotate( -1deg )';
}
else if ( Keys.right ) {
document.querySelector( 'div' ).style.transform += 'rotate( 1deg )';
}
requestAnimationFrame( update );
}
requestAnimationFrame( update );
</script>