简体   繁体   中英

Javascript ball bouncing back and forth indefinitely

I'm writing a simple JS function that draws a ball in canvas and just bounces it back and forth between the left and right borders of the screen indefinitely. I currently have it starting on the left side and going right. How I have it currently, it goes to the right but then gets stuck on the right edge; it doesn't bounce back. Any tips?

        var dx=4;
        var dy=4;
        var y=150;
        var x=10;
       function draw(){
          context= myCanvas.getContext('2d');
          context.clearRect(0,0,htmlCanvas.width,htmlCanvas.height);
          context.beginPath();
          context.fillStyle="#0000ff";
          context.arc(x,y,50,0,Math.PI*2,true);
          context.closePath();
          context.fill();
          if(x<htmlCanvas.width)
            x+=dx
          if(x>htmlCanvas.width)
            x-=dx;
        }
setInterval(draw,10); 

Change this:

if(x<htmlCanvas.width)
    x+=dx
if(x>htmlCanvas.width)
    x-=dx;

to this:

// move the ball
x += dx;

if (x > htmlCanvas.width - 50) {
   // if we hit the right edge, get back in bounds
   x = htmlCanvas.width - 50;
   // and reverse direction
   dx *= -1;
} else if (x < 50) {
   // if we hit the left edge, get back in bounds
   x = 50;
   // and reverse direction
   dx *= -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM