-2

I want to make a pong game using HTML, CSS and javascript. I started with making a player and I got it to move using the arrow keys but it can go outside the screen which creates the sidebar. I want it to not be able to go off the screen. Here is the javascript code:

const right = document.getElementById("right");

const player = document.createElement("player");
player.classList.add("player");
right.appendChild(player);

player.style.top = "300px";
player.style.left = 5;

let moveBy = 10;
window.addEventListener("keydown", (event) => {
  switch (event.key) {
    case "ArrowUp":
      player.style.top =
        parseInt(player.style.top) - moveBy + "px";
      break;
    case "ArrowDown":
      player.style.top =
        parseInt(player.style.top) + moveBy + "px";
      break;
  }
});

I tried adding if statements but it did not work, I have also tried to google it but I have not found the right answer for this.

kika
  • 1
  • 2
  • You did not set the boundary at all. Is the browser area your boundary? or is there a specific DIV for the "move zone"? – Raptor Jul 21 '23 at 02:52
  • The browser should be the boundary, I tried adding it using if statements, and I got it to stay inside but if I were to try and run it on another screen it would not work because the screens are different sizes. I don't know how to get the height of the browser area. I tried using screen.height, but that returns the height of the whole screen, not just the browser page. – kika Jul 21 '23 at 03:19

1 Answers1

0

You need position: absolute; to make top setting work.

player.style.position = "absolute";

Then set the range of top (0 ~ window.innerHeight)

let top,
  max = window.innerHeight - 30;
switch (event.key) {
  case "ArrowUp":
    top = parseInt(player.style.top) - moveBy;
    break;
  case "ArrowDown":
    top = parseInt(player.style.top) + moveBy;
    break;
}
player.style.top = top > max ? max : top < 0 ? 0 : top + "px";
Shuo
  • 1,512
  • 1
  • 3
  • 13