


if(Math.abs(this.vx) < 0.01){ this.vx = 0; } else this.vx += this.vx>0? -mocali*t : mocali*t;
this.vy = this.vy + g * t; this.x += t * this.vx * pxpm; this.y += t * this.vy * pxpm;
if(this.y > canvas.height - ballRadius || this.y < ballRadius){ this.y = this.y < ballRadius ? ballRadius : (canvas.height - ballRadius); this.vy = -this.vy*collarg } if(this.x > canvas.width - ballRadius || this.x < ballRadius){
}
小球的动作方法也很简单,就两个,第一个方法是把自己画出来,第二个方法就是控制小球的运动。t是当前帧与上一帧
的时间差。用于计算小球的速度的增量从而得出小球的位移增量,从而计算出小球的新位置并且将小球重绘。得出新位置的同
时判断小球的新位置有无超出墙壁,如果超出则进行速度修正让小球反弹。
第二个方法里的一些常量ballRadius =30, g = 9.8 , mocali = 0.5,balls = [],collarg = 0.8,pxpm = canvas.width/20; 意思很明
显:ballradius是球半径,g是重力加速度,mocali是空气阻力引起的水平方向的减速度,balls是一个用于存放小球对象的数
组,collarg是弹力系数。pxpm是像素与米之间的映射,把画布当成是20米宽的区域。
【碰撞检测】
创建好小球对象后,就开始写碰撞了,小球与小球之间的碰撞:
复制代码
代码如下:
function collision(){
for(var i=0;i //获得碰撞后速度的增量
var ax = ((b1.vx - b2.vx)*Math.pow((b1.x - b2.x) , 2) + (b1.vy - b2.vy)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)
var ay = ((b1.vy - b2.vy)*Math.pow((b1.y - b2.y) , 2) + (b1.vx - b2.vx)*(b1.x - b2.x)+(b1.y - b2.y))/Math.pow(rc , 2) //
给与小球新的速度
b1.vx = (b1.vx-ax)*collarg;
b1.vy = (b1.vy-ay)*collarg;
b2.vx = (b2.vx+ax)*collarg;
b2.vy = (b2.vy+ay)*collarg; //获取两球斜切位置并且强制扭转
var clength = ((b1.radius+b2.radius)-rc)/2;
var cx = clength * (b1.x-b2.x)/rc;
var cy = clength * (b1.y-b2.y)/rc;
b1.x = b1.x+cx;
b1.y = b1.y+cy;
b2.x = b2.x-cx;
b2.y = b2.y-cy;
}
}
}
}
}
每一帧都进行小球之间碰撞的判断,如果两个小球球心距离小于两球半径之和,则证明两个小球发生了碰撞。然后进行计
算两个小球碰撞之后的速度变化量。ax和ay就是速度变化量。
后面长长的公式就是这个:
具体原理我就不说了,想了解原理就直接戳 小球碰撞的算法设计 。 下面那段就是防止小球重复碰撞检测导致无法正常反弹,
所以计算两小球的球心距离,然后算出两个小球的斜切位置,并且将两个小球的位置进行更正。
【运动动画】
最后一步:
canvas.onclick = function(event){ event = event || window.event; var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - canvas.offsetLeft; var y= event.clientY + document.body.scrollTop + document.documentElement.scrollTop - canvas.offsetTop;
balls.forEach(function(){ this.vx = (x - this.x)/20; //初速度 m/s this.vy = (y - this.y)/20; }); }
function animate(){ ctx.save(); ctx.fillStyle = "rgba(255,255,255,0.2)"; ctx.fillRect(0,0,canvas.width,canvas.height) ctx.restore(); // ctx.clearRect(0,0,canvas.width,canvas.height)
var t1 = new Date(); var t = (t1 - t0)/1000; collision(); balls.forEach(function(){ this.run(t); }); t0 = t1;
if("requestAnimationFrame" in window){ requestAnimationFrame(animate); } else if("webkitRequestAnimationFrame" in window){ webkitRequestAnimationFrame(animate); } else if("msRequestAnimationFrame" in window){ msRequestAnimationFrame(animate); } else if("mozRequestAnimationFrame" in window){ mozRequestAnimationFrame(animate); } } }
通过点击画布的位置来给于小球初速度,然后animate就是动画的每一帧运行的方法。上面的 ctx.fillStyle = "rgba(255,255,255,0.2)"; ctx.fillRect(0,0,canvas.width,canvas.height)是给小球添加虚影,我觉得这样会更好看,如果觉得不 喜欢,就直接用clearRect清除就行了。然后就是计算每一帧的时间差,然后对小球数组里小球数组进行遍历重绘。然后再加 入碰撞检测的collision方法。动画也就做完了。 至此,就已经写完了,源码地址: https://github.com/whxaxes/canvas-test/blob/gh-pages/src/Other-demo/shotBall.html