Before the use of the "uniform" ball collision with the wall or floor of the calculation method.
Suddenly found that the small ball collision, in fact, a part of the ball into the inside of the wall, in the small ball speed is not fast, perhaps not obvious, but when the ball speed becomes faster, the ball radius is larger, you can not see
The effect is as follows
The code is as follows (all code is only available under Chrome or Safari, because the Requestanimationframe method is not write-compatible):
<!doctype html>varCanvas_width = 800;varCanvas_height = 600;varBall =function(){ This. x = 100; This. y = 100; This. R = 50; This. VX = 30;} Ball.prototype.draw=function(CTX) {Ctx.beginpath (); Ctx.arc ( This. x, This. Y, This. r,0,math.pi*2); Ctx.fill (); Ctx.closepath ();} Ball.prototype.update=function (){ This. x + = This. VX; if( This. x <= This. R | | This. x >= Canvas_width- This. R) { This. VX =- This. VX; }}window.onload=function (){ varOcanvas = document.getElementById ("Canvas"); varCTX = Ocanvas.getcontext ("2d"); varBall =NewBall (); Gameloop (); functionGameloop () {window.webkitrequestanimationframe (Gameloop) ctx.clearrect (0,0, Canvas_width,canvas_height); Ball.draw (CTX); Ball.update (); }}</script>Want to good effect, sure enough, not easy to figure out.
The problem arises when the ball is larger than the distance that can be moved before hitting the wall, so the current speed minus the remaining moving distance is the ball's distance to the wall.
The solution is not difficult, but it is not clear at the moment whether it is feasible to apply this to complex motion.
The implementation code is as follows:
<!doctype html>varCanvas_width = 800;varCanvas_height = 600;varBall =function(){ This. x = 100; This. y = 100; This. R = 50; This. VX = 30;} Ball.prototype.draw=function(CTX) {Ctx.beginpath (); Ctx.arc ( This. x, This. Y, This. r,0,math.pi*2); Ctx.fill (); Ctx.closepath ();} Ball.prototype.update=function (){ if( This. x <= This. R + Math.Abs ( This. VX) && This. VX < 0 ){ This. x = This. R; This. VX =- This. VX; }Else if( This. x >= Canvas_width- This. R-math.abs ( This. VX) && This. VX > 0 ){ This. x = Canvas_width- This. R; This. VX =- This. VX; }Else{ This. x + = This. VX; }}window.onload=function (){ varOcanvas = document.getElementById ("Canvas"); varCTX = Ocanvas.getcontext ("2d"); varBall =NewBall (); Gameloop (); functionGameloop () {window.webkitrequestanimationframe (Gameloop) ctx.clearrect (0,0, Canvas_width,canvas_height); Ball.draw (CTX); Ball.update (); } }</script>The solution to the y-axis is not to repeat
----Kill error in a small ball colliding wall