Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you reverse the direction of a ball if continuously going in one direction?

enter image description hereI have declared my global variables, followed by a function to move the ball, then followed by a setInterval. However, I can’t seem to figure the right way to reverse the ball that continuously moves to the right of my screen until no longer visible. Is it a matter of a type of reverse method or setting up conditions?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Let me give you some insights:

to set up a collision you could get the y of the ball + or – radius and see if it’s greater than of that of the border or less than zero…

like this:

if (y + radius > innerHeight) and else if (y - radius < 0)

then you could compare the x similarly:

if (x + radius > innerWidth) and else if (x - radius < 0)

by velocity *= -1 or velocity = 0-velocity you can reverse the direction of the ball.

you can see this tutorial for more: https://www.geeksforgeeks.org/how-to-build-a-bounce-ball-with-html-and-javascript/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading