I'm creating a simple asteroids-like game in CSS and JS using the DOM over canvas for...experimentation purposes.
My code is pretty small in this example to make it easy to see what's going on below. The ultimate goal: Let arrow keys smoothly rotate and translate the spaceship around the window without creating an infinite amount of transforms. I think I'm 90% there:
Use the arrow keys to control the snippet below.
'use strict';
function defineDistances() {
var distance = {};
distance.up = -1;
distance.right = 1;
distance.down = 1;
distance.left = -1;
return distance;
}
function defineKeys() {
var keys = {};
keys.up = 38;
keys.right = 39;
keys.down = 40;
keys.left = 37;
return keys;
}
function checkKeys( e ) {
var triBx = document.getElementById( 'v-wrp' ),
keys = defineKeys(),
distance = defineDistances();
switch( e.keyCode ) {
case keys.up:
triBx.style.transform += 'translateY(' + distance.up + 'px)';
break;
case keys.right:
triBx.style.transform += 'rotate(' + distance.right + 'deg)';
break;
case keys.down:
triBx.style.transform += 'translateY(' + distance.down + 'px)';
break;
case keys.left:
triBx.style.transform += 'rotate(' + distance.left + 'deg)';
break;
}
}
function detectMovement( e ) {
setInterval (
function() {
checkKeys( e );
},
1000/24
);
}
function start() {
window.addEventListener( 'keydown', detectMovement );
preventBrowserWindowScroll()
}
start();
@import url( "https://fonts.googleapis.com/css?family=Nunito" );
html {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
font-family: "Nunito", sans-serif;
font-size: 2rem;
}
.v {
display: block;
transform: rotate( 180deg );
}
<div id="v-wrp" class="v-wrp">
<b class="v">V</b>
</div>
<script>
function preventBrowserWindowScroll() {
window.addEventListener( 'keydown', function( e ) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf( e.keyCode ) > -1 ) {
e.preventDefault();
}
}, false )
}
</script>
If you inspect the v-wrp
element in the browser you can see the transforms get added endlessly.
The reason I use +=
to add transforms is to avoid this problem: Reset CSS transform origin after translation / rotation
( The transform-origin
doesn't move with the element as it moves, causing undesired effects unless all transforms are added in addition to the previous ones... )
So how do I overcome these challenges? I suspect the snippet is so choppy because of the endless transforms being added. How do I get this working similarly to the way it is now without all the memory loss/ choppiness/ bugginess / endless transforms?
Edit: Another major problem is how the ship will travel in the same directions continuously once the keys are pressed, even going in a circular like pattern if you hit the correct keys. I want it to drift like in space but not turn once the keys are let go. The trajectory should stay straight as it "floats" What am I doing wrong?.