0
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
3 Respuestas
+ 5
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
+ 3
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
0
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