简体   繁体   中英

Make a Bouncing Ball with Canvas in Javascript

How do I make the ball start in an upwards motion?

I am super lost here and have tried to many things to mention and I know I am missing something simple.

I know this is the part of the code that I need to change, and that it has to do with the if statement for x, but that is far as I have gotten.

function update() {
    x += 1;
    y += yspeed;
    yspeed += gravity;
    if ( y >= context.canvas.height)
    {
        yspeed *= -1;
    }
    if ( x <= 0 || x >= context.canvas.width)
    {
        x = (x + context.canvas.width) % context.canvas.width;
    }
  }

Right now the ball starts out bouncing downward. How do I change it to starting out bouncing upward?

yspeed determines the vertical speed of your ball - and it must be defined somewhere. Try changing it to a negative value like -10. What it actually pulls it down to the ground is gravity .

Here's an example [Hit 'Run code snippet' to see it in action]:

 var gravity = 1; var yspeed = -10; var x = 10; var y = 50; document.getElementById("ball").style.left = x + "px"; document.getElementById("ball").style.top = y + "px"; function loop() { document.getElementById("ball").style.left = x + "px"; document.getElementById("ball").style.top = y + "px"; x += 1; y += yspeed; yspeed += gravity; } var interval = setInterval(loop, 60); 
 <svg height="20" width="20" id="ball" style="position:relative"> <circle cx="10" cy="10" r="10" fill="red" /> </svg> 

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