JSFiddle - React, Tailwind, and code Playground
HTML
<p>Use keys a, s, d, w. Note that you can press two keys at once for diagonal movement. (Probably will need to click on the document so that it can get focus and start receiving key events.)</p>
<div>Test</div>
CSS
div {
position : absolute;
left : 100px;
top: 100px;
width : 40px;
height : 40px;
background-color : blue;
}
JavaScript
$(document).ready(function(e){
var keys = {};
$(document).keydown(function(event){
keys[event.which] = true;
}).keyup(function(event){
delete keys[event.which];
});
var $d = $("div");
function gameLoop() {
if (keys[68]) { // d for east
$d.css("left", function(i,oldVal) { return parseInt(oldVal) + 2 + "px"; });
}
else if (keys[65]) { //press a for west
$d.css("left", function(i,oldVal) { return parseInt(oldVal) - 2 + "px"; });
}
if (keys[83]) {
$d.css("top", function(i,oldVal) { return parseInt(oldVal) + 2 + "px"; });
}
else if (keys[87]) {
$d.css("top", function(i,oldVal) { return parseInt(oldVal) - 2 + "px"; });
}
// etc. for other keys
// code to move objects and repaint canvas goes here
setTimeout(gameLoop, 20);
}
gameLoop();
$(document).focus();
});