Search code examples
javascripthtml2d-games

making a game where a ball bounces of side of screen and doesen't


I am working on this code from a tutorial on Udemy where I am trying to make Pong. I am in the early stages and just want to have the ball bounce off the edge of a screen. It doesn't though. I think the problem might be where I define

ballspeedx = -ballspeedx

Here is my code:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
  <canvas id="gameCanvas" width="800" height="600">
    
      </canvas>
  <script type="text/javascript">
    var canvas;
    var canvasContext;
    var ballx = 50
    var ballspeedx = 12;

    window.onload = function() {
      var FPS = 80
      setInterval(function() {
        moveEverything();
        drawEverything();
      }, 10000 / FPS)

    }

    function moveEverything() {
      ballx = ballx + ballspeedx;
      if (ballx > 800) {
        console.log("GREATER THAT 800")
        ballspeedx = -ballspeedx
        ballspeedx = ballspeedx + ballspeedx

        console.log("Hello?")
      }
      if (ballx > 0) {
        ballspeedx = 5;
      }

    }

    function drawEverything() {
      ballx = ballx + 5;
      console.log(ballx)
      canvas = document.getElementById('gameCanvas');
      canvasContext = canvas.getContext('2d')
      canvasContext.fillStyle = 'black';
      canvasContext.fillRect(0, 0, canvas.width, canvas.height);
      canvasContext.fillStyle = 'white';
      canvasContext.fillRect(0, 210, 20, 100);
      canvasContext.fillStyle = 'red';
      canvasContext.fillRect(ballx, 100, 10, 10);

    }
  </script>
</body>

</html>

Thanks in advance.


Solution

  • The problem is in the block

    if (ballx > 0) {
       ballspeedx = 5;
    }
    

    If the ball is on the rightmost edge (800), it's still greater than zero. So even if you flip the velocity (which is what you're supposed to do), that automatically sets it to continue going further to the right. I changed your moveEverything() function to this and it worked fine:

    function moveEverything() {
      ballx = ballx + ballspeedx;
      if (ballx > 800 || ballx < 0) {
        ballspeedx = -ballspeedx;
        ballx += ballspeedx;
      }
    }
    

    Also, you shouldn't move the ball in drawEverything(), that's just bad design.