function gamestart(){
var gr;
var gr = true;
console.log(gr==true);
if(gr == true){
console.log("we have activated pointer key detection dear Mr.ketsebaot")
document.onkeydown = checkk;
}
}
function checkk(e){
console.log(e.keyCode)
if(e.keyCode == 38){
if(document.getElementById('player-one').getBoundingClientRect().top < 503){
e.preventDefault();
var vertical = document.getElementById('player-one').getBoundingClientRect().top;
document.getElementById("player-one").style.top = vertical - 0.5 + "px";
console.log(vertical)
}
else{
e.preventDefault();
}
}
if(e.keyCode == 40){
e.preventDefault();
var verticalb = document.getElementById('player-one').getBoundingClientRect().top;
var newv;
var newv = verticalb+0.5
console.log("new top value: "+newv)
document.getElementById("player-one").style.top = newv +"px";
}
}
.player-one{
position: relative;
top: 50px;
left: 10px;
width: 25px;
height: 65px;
background-color: aliceblue;
}
<div className='player-one' id='player-one'></div>
<h1 onClick={gamestart()}>Press to start</h1>
i have a query. i wrote a javascript function that detects keyboard input and moves the 'player-one' div based on arrow key presses.
function checkk(e){
console.log(e.keyCode)
if(e.keyCode == 38){
if(document.getElementById('player-one').getBoundingClientRect().top < 503){
e.preventDefault();
var vertical = document.getElementById('player-one').getBoundingClientRect().top;
document.getElementById("player-one").style.top = vertical - 0.5 + "px";
console.log(vertical)
}
else{
e.preventDefault();
}
}
if(e.keyCode == 40){
e.preventDefault();
var verticalb = document.getElementById('player-one').getBoundingClientRect().top;
console.log(verticalb)
console.log("0.5")
var newv;
var newv = verticalb+0.5
console.log(newv)
document.getElementById("player-one").style.top = newv +"px";
console.log(newv)
}
}
However, it seems like the code is not functioning correctly as the top value for 'player-one' div keeps increasing regardless of whether I subtract or add 0.5.
here is my css styling for player-one:
.player-one{
position: relative;
top: 50px;
left: 10px;
width: 25px;
height: 65px;
background-color: aliceblue;
}
I attempted to decrease the top value when the up arrow key was pressed, and increase it when the down arrow key was pressed, but unfortunately, it seems to be increasing in both cases.