学canvas学了有一个多礼拜了,觉得canvas真心好玩。学canvas的人想法估计都跟我差不多,抱着写游戏的态度去学canvas的。所以运动学啊、碰撞检测啊、一些简单的算法神马的是基础啊。以前没做过游戏的我学起来还真心吃力。今天就来说下用canvas写个最简单的弹力球游戏,就运用了最简单的重力作用以及碰撞检测。
先上DEMO:弹力球DEMO (鼠标点击canvas里的空白区域会给与小球新速度)
【创建小球对象】
第一步就是先创建一个小球对象,写好小球的构造函数:
复制代码
var Ball = function(x , y , r , color){
this.x = x;
this.y = y;
this.oldx = x;
this.oldy = y;
this.vx = 0;
this.vy = 0;this.radius = r;
this.color = color;
}
小球属性很简单,xy是小球的坐标,vx和vy是小球的初始水平速度和初始垂直速度。radius就是小球的半径,color是小球颜色(为了区分不同球),oldx和oldy是记录小球的上一帧的位置,后期球与球之间碰撞后用于位置修正(后面其实没用上,位置修正直接计算了,如果用oldx来设置很不严谨,不过记录一下,难免会用得到)。
小球属性写好后,就在小球原型中写小球的动作了:
复制代码
Ball.prototype = {
paint:function(){
ctx.save();
ctx.beginPath();
ctx.arc(this.x , this.y , this.radius , 0 , Math.PI*2);
ctx.fillStyle=this.color;
ctx.fill();
ctx.restore();
this.moving = false;
},
run:function(t){
if(!this.candrod) {
this.paint();
return};
this.oldx = this.x;
this.oldy = this.y;</p>
<p>
if(Math.abs(this.vx) < 0.01){
this.vx = 0;
}
else this.vx += this.vx>0? -mocali*t : mocali*t;</p>
<p> this.vy = this.vy + g * t;
this.x += t * this.vx * pxpm;
this.y += t * this.vy * pxpm;</p>
<p> 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){
this.x = this.x < ballRadius ? ballRadius : (canvas.width – ballRadius);
this.derectionX = !this.derectionX;
this.vx = -this.vx*collarg;
}
this.paint();
},</p>
<p> }
小球的动作方法也很简单,就两个,第一个方法是把自己画出来,第二个方法就是控制小球的运动。t是当前帧与上一帧的时间差。用于计算小球的速度的增量从而得出小球的位移增量,从而计算出小球的新位置并且将小球重绘。得出新位置的同时判断小球的新位置有无超出墙壁,如果超出则进行速度修正让小球反弹。









