Reputation: 323
I've created an article with a red background, you can move it using WASD keys, however, the real trouble comes in when I try to create a diagonal movement (for ex, if W and D are pressed, the article should go to the top right corner), it doesn't seem to work:
document.body.addEventListener('keypress', function(event) {
var oldLeft = getComputedStyle(document.body).left,
newLeft;
var oldTop = getComputedStyle(document.body).top,
newTop;
oldLeft = parseInt(oldLeft, 10);
oldTop = parseInt(oldTop, 10);
console.log(event);
if ( event.key == 'a') {
newLeft = oldLeft - 10;
}
else if ( event.key == 'd') {
newLeft = oldLeft + 10;
}
else if (event.key == 'w') {
newTop = oldTop - 10;
}
else if (event.key == 's') {
newTop = oldTop + 10;
}
//HERE
if ((event.key =='w') || (event.key == 'd')) {
newLeft = oldLeft + 10;
newTop = oldTop - 10;
}
document.body.style.left = newLeft + 'px';
document.body.style.top = newTop + 'px';
});
article {
width: 33.75em;
padding: 1.5em;
margin: 0 auto;
background: #f6be00;
/*border: 4px solid white;*/
border-radius: 1.25em;
position: relative;
left: 0;
}
body {
position: relative;
background: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/styles.css">
<title>Javascript</title>
</head>
<body>
<article class="article">
<ul id="browser">
</ul>
<ul id="user">
</ul>
</article>
<script src="javascript/main.js"></script>
</body>
</html>
It goes to the top right corner but that happens even when I don't press W and D at the same time.
Upvotes: 2
Views: 675
Reputation: 191996
Use keydown
events to collect keys to an array, and keyup
events to wait until all keys are un-pressed to execute the changes:
var clicked = {};
document.body.addEventListener('keydown', function(event) {
clicked[event.key] = false; // collect keys an init as false
});
document.body.addEventListener('keyup', function(event) {
clicked[event.key] = true; // change keys to true
// if not all keys are true don't execute anything
if (!Object.values(clicked).every(Boolean)) return;
var left = parseInt(getComputedStyle(document.body).left, 10);
var top = parseInt(getComputedStyle(document.body).top, 10);
// get the clicked keys
const keys = Object.keys(clicked);
// iterate them and change the values
keys.forEach(function(key) {
switch (key) {
case 'a':
{
left -= 10;
break;
}
case 'd':
{
left += 10;
break;
}
case 'w':
{
top -= 10;
break;
}
case 's':
{
top += 10;
break;
}
}
});
clicked = {}; // clear clicked keys
document.body.style.left = left + 'px';
document.body.style.top = top + 'px';
});
article {
width: 33.75em;
padding: 1.5em;
margin: 0 auto;
background: #f6be00;
/*border: 4px solid white;*/
border-radius: 1.25em;
position: relative;
left: 0;
}
body {
position: relative;
background: red;
}
<article class="article"></article>
Upvotes: 2