Have a very small snippet of an asteroids-like game I'm working on using only the DOM without Canvas. I have the "ship" moving pretty smoothly when arrow keys are pressed but how would I go about giving the ship momentum? When the user releases a key I don't want the ship to stop. I'm trying to simulate the physics of space a little bit. How could I get this ship to keep moving in the direction it was going while allowing it to rotate freely without traveling in the direction it's currently pointing ( unless up arrow is being pressed )? Ideas?
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>
Use the arrow keys to control snippet.