Why my code is acting weird? | SoloLearn: Learn to code for FREE!


Why my code is acting weird?

I made this bouncing ball but sometimes the ball becomes slow and sometimes it becomes fast .. why? https://code.sololearn.com/W9P7MaZVuaJv/?ref=app

2/12/2020 12:25:40 PM

Plaban Kr. Mondal

3 Answers

New Answer


Plaban Kr. Mondal , I'm not able to see "weird" behavior that you mentioned. probably using requestAnimationFrame instead of setInterval can solve your problem. For rAF you need to modify code as follows : function drawTheBall(){ requestAnimationFrame(drawTheBall);//call rAF within function. ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath() ctx.fillStyle = ball.color ctx.arc(ball.x, ball.y, ball.radi, 0, 2 * Math.PI) ctx.fill() ctx.closePath() ballMovement() } drawTheBall() also remove setInterval(drawTheBall,5) by this you are actually trying to call drawTheBall function 200 time per second! https://stackoverflow.com/questions/38709923/why-is-requestanimationframe-better-than-setinterval-or-settimeout


because speed of ball along Y axis is random and random is not same always. that's why it's sometimes fast and sometimes slow. This is line 17 : let vy = 2 + (Math.random() * 10) //movement in y axis of this code https://code.sololearn.com/W9P7MaZVuaJv/?ref=app


But still even if I just remove Math.random().. it seems like sometimes ball is just stuck for a moment and then again it starts jumping