Don't know why, but the collision of ball with in the canvas is not behaving properly after some time.
I applied all the physics/maths/vector law I know.
not working yet
I think, main problem is on line 59. But I couldn't figure out that problem.
Try messing around with this code
Click the canvas to pause/play
As you can see, when the ball hit the right wall and coming from bottom to top, it actually hits twice because of the new angle given to it
You should calculate the new angle that should be added on a wall hit
I suggest the isCollided function will return either 0 or the angle that should be added (you should calculate it in a seperate function)
you can notice when using high velocity the ball may go beyond the wall, but due to the direction check, it won't change direction uncontrolably
You need to address the direction of the ball in the collision calculations as well.
What happens is that due to the ball velocity, it sometimes overlaps with the walls more than you'd want.
When that happens you are likely to get a positive collisions in a row, and as a result change the direction multiple times.
Just increase the velocity and see it occurs much more often
Sarthak 🇳🇵 yeah I think I know what happens: sometimes, in a corner, it crosses both a vertical and a horizontal boundary, whereas isCollided(), as soon as it finds one of them, returns without checking the other. I changed it to verify both conditions now, so far seems to work well.
EDIT: by working well I mean the ball doesn't get lost anymore. If you want it to not cross the lines at all, I'll have to make a little change, which I didn't want to make because it will change the trajectory in a way I didn't want to.
Yes, you were right. When velocity is 1, everything goes right. But when velocity is higher, the direction of ball sometimes changes twice/more.
I'll try to correct it by limiting the velocity before overlapping with walls
The ball still crosses the wall when velocity is increased.
I tried to debug the code and the following are the results.