0
I am developing a game in which the user presses the arrow keys (left, up, right, down) and the character moves without leaving the area where he is or is going to see a "collision", but for this I need the <div id="player">
stay inside the <div id="zone">
without going out of it I "managed" to do it using the method getBoundingClientRect()
:
JS / CSS / HTML
let zone = document.querySelector("#zone");
let player = document.querySelector("#player");
let axisX = 0;
let axisY = 0;
window.addEventListener("keydown", playerMovement);
function playerMovement() {
let key = event.keyCode;
if (key == 37) {
axisX -= 10;
player.style.left = `${axisX}px`;
}
else if (key == 38) {
axisY -= 10;
player.style.top = `${axisY}px`;
}
else if (key == 39) {
axisX += 10;
player.style.left = `${axisX}px`;
}
else if (key == 40) {
axisY += 10;
player.style.top = `${axisY}px`;
}
if (player.getBoundingClientRect().x <= zone.getBoundingClientRect().x) {
axisX = 0;
player.style.left = `${axisX}px`;
}
else if (player.getBoundingClientRect().y <= zone.getBoundingClientRect().y) {
axisY = 0;
player.style.top = `${axisY}px`;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#zone {
width: 400px;
height: 200px;
border: 2px solid #505050;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#player {
width: 100px;
height: 100px;
background: #505050;
position: relative;
}
<div id="zone">
<div id="player"></div>
</div>
But the problem is that it only works if the player
get out of zone
on the left or upper side, in the case of player
is moved to the right or down, it ends up coming out of the zone
and that’s the part where I don’t know how to get you into the zone
, in case he goes to one of these sides.
Vlw! @Sergio was this msm!
– marquinho