Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So Im new to javascript and trying to make a ball i designed bounce off the canvas so far i made it go down the bounce back up once it touches the canvas but when it comes back up it wont go down for some unknown reason.

It would also be of some help if i could get an explanation of how i could make this ball bounce horizontally on the left and right of the canvas

What I have tried:

<!DOCTYPE html>

<html>

<head>
  <meta charset="UTF-8">
  <title>Canvas</title>

  <style type="text/css">
    body {
      background-color: white;
    }
  </style>

</head>

<body>
  <h1>Akeem Jokosenumi</h1>
  <canvas id="canvas-for-ball" width="300" height="300" style="border:1px solid"></canvas>

  <script type="text/javascript">
    // Gets a handle to the element with id canvasOne.
    var canvas = document.getElementById("canvas-for-ball");
    // Get a 2D context for the canvas.
    var ctx = canvas.getContext("2d");


    // The vertical location of the ball.
    var yPos = 10;
    var yVel = 2;

    // A function to repeat every time the animation loops.
    function repeatme() {
      ctx.clearRect(0, 0, 300, 300)
      // Draw the ball (stroked, not filled).
      ctx.beginPath();
      ctx.arc(70, yPos, 7, 0, 2 * Math.PI);
      ctx.stroke();

      // Update the y location.
      yPos += yVel;
      console.log(yPos);

      if (yPos > 290)
      yVel *= -1;
      
       if(yPos < 290){
        yVel *= 1;
      }
     // else if (yPos < 290)
     // yVel += 1;
      

      window.requestAnimationFrame(repeatme);
    }

    // Get the animation going.
    repeatme();


  </script>

</body>

</html>
Posted
Updated 7-Oct-21 22:22pm

1 solution

Quote:
JavaScript
if(yPos < 290){
    yVel *= 1;
}
What do you think that block is going to do? If you're moving back up (yVel < 0), multiplying the velocity by 1 isn't going to change it.

-2 × 1 === -2

You need to test whether the object is too far up, and then multiply the velocity by -1 again.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900