Reputation: 11
I made an object out of a div in html and CSS to make a player for my game I am making and I can't get the player to move when I press the arrow keys. Does anyone know what is wrong with my code?
Here is the Javascript:
var player = document.getElementById("player");
var velocity = 5;
let player = {
height:20,
width:20,
x:200,
y:200
}
document.addEventListener("keydown", function(event){
if(event.keyCode === 37){
player.x -= velocity:
else if(event.keyCode ===38){
player.y -=velocity;
}
});
What is wrong?
Upvotes: 0
Views: 466
Reputation: 2869
With an addition to Ibnelaiq's answer, here's a way to make sure the players can move better -
var key = [];
function keys(db, e) {
var code = e.which || e.keyCode;
if (db == false && key.includes(code) === false) {
key.push(code);
} else if (db === true) {
key.splice(key.indexOf(code));
}
}
setInterval(() => {
console.log(key);
}, 30);
document.getElementsByClassName('game')[0].getContext('2d').fillText('Click here and press keys', 10, 10);
.game {
background-color: #f1f1f1;
outline: none;
border: 1px solid black;
}
<canvas class='game' tabindex='1' width='400px' height='290px' onkeydown='keys(false, event)' onkeyup='keys(true, event)'>
What this does:
<canvas>
(not limited to <canvas>
though) waits for keydown
and adds event.keycode
or event.which
to the array. It also waits for keyup
, and removes whatever event.keycode
or event.which
was released from the array.
The setInterval
is just there to log the array into the console. The last line in the code is there to write text into <canvas>
.
Of course, you can add his switch
statement into the setInterval
, but in there only.
Upvotes: 0
Reputation: 1966
Moving a div using simple Javascript
just adding switch on keydown event on document and then customzing the css of div (player) top-left
var player = $('#player');
var velocity = 5;
$(document).keydown(function(e) {
switch (e.which) {
case 37:
player.css('left', player.offset().left - velocity);
break;
case 38:
player.css('top', player.offset().top - velocity);
break;
case 39:
player.css('left', player.offset().left + velocity);
break;
case 40:
player.css('top', player.offset().top + velocity);
break;
}
})
#player {
background: #ccc;
height: 50px;
width: 50px;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<div id="player"></div>
</body>
</html>
Upvotes: 1