标签:
之前一直在沿用之前听课学来的"千篇一律"的小球碰撞墙壁或者地板的计算方法.
忽然发现,小球碰撞的时候,其实小球有一部分是进入了墙的里面,在小球速度并不快的情况下,或许不明显,但是当小球速度变的更快,小球半径也更大的时候,就没法看了
效果如下
代码如下(所有代码都只在chrome或者safari下能用,因为requestAnimationFrame方法我并没有写兼容):
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script> var CANVAS_WIDTH = 800; var CANVAS_HEIGHT = 600; var Ball = 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 (){ var oCanvas = document.getElementById("canvas"); var ctx = oCanvas.getContext("2d"); var ball = new Ball(); gameLoop(); function gameLoop(){ window.webkitRequestAnimationFrame(gameLoop) ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT); ball.draw(ctx); ball.update(); } } </script> </head> <body> <canvas id="canvas" width="800" height="600" style="display:block; margin:10px auto; border:1px solid #ccc;"></canvas> </body> </html>
想要好效果,果然不能图省事儿.
问题出现于小球在撞击墙壁之前,速度大于改变方向之前可以运动的距离,因此,当前速度减去剩下可运动的距离,就是小球进入墙壁的距离.
解决方法也不难,只是,目前并不清楚在应用到复杂运动的时候,这种写法还是否可行
实现代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script> var CANVAS_WIDTH = 800; var CANVAS_HEIGHT = 600; var Ball = 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 (){ var oCanvas = document.getElementById("canvas"); var ctx = oCanvas.getContext("2d"); var ball = new Ball(); gameLoop(); function gameLoop(){ window.webkitRequestAnimationFrame(gameLoop) ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT); ball.draw(ctx); ball.update(); } } </script> </head> <body> <canvas id="canvas" width="800" height="600" style="display:block; margin:10px auto; border:1px solid #ccc;"></canvas> </body> </html>
Y轴方向的解决方法就不再赘述
标签:
原文地址:http://www.cnblogs.com/liqingchang/p/4478004.html