學canvas學了有一個多禮拜了,覺得canvas真心好玩。學canvas的人想法估計都跟我差不多,抱著寫游戲的態(tài)度去學canvas的。所以運動學啊、碰撞檢測啊、一些簡單的算法神馬的是基礎(chǔ)啊。以前沒做過游戲的我學起來還真心吃力。今天就來說下用canvas寫個最簡單的彈力球游戲,就運用了最簡單的重力作用以及碰撞檢測。
先上DEMO:彈力球DEMO (鼠標點擊canvas里的空白區(qū)域會給與小球新速度)
【創(chuàng)建小球?qū)ο蟆?/p>
第一步就是先創(chuàng)建一個小球?qū)ο螅瑢懞眯∏虻?a href='http://www.survivalescaperooms.com/tag/gouzaohanshu_945_1.html' target='_blank'>構(gòu)造函數(shù):
代碼如下:
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;
}
小球?qū)傩院芎唵危瑇y是小球的坐標,vx和vy是小球的初始水平速度和初始垂直速度。radius就是小球的半徑,color是小球顏色(為了區(qū)分不同球),oldx和oldy是記錄小球的上一幀的位置,后期球與球之間碰撞后用于位置修正(后面其實沒用上,位置修正直接計算了,如果用oldx來設(shè)置很不嚴謹,不過記錄一下,難免會用得到)。
小球?qū)傩詫懞煤螅驮谛∏蛟椭袑懶∏虻膭幼髁耍?/p>
代碼如下:
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.p
return};
this.oldx = this.x;
this.oldy = this.y;
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){
this.x = this.x < ballRadius ? ballRadius : (canvas.width - ballRadius);
this.derectionX = !this.derectionX;
this.vx = -this.vx*collarg;
}
this.paint();
},
}
小球的動作方法也很簡單,就兩個,第一個方法是把自己畫出來,第二個方法就是控制小球的運動。t是當前幀與上一幀的時間差。用于計算小球的速度的增量從而得出小球的位移增量,從而計算出小球的新位置并且將小球重繪。得出新位置的同時判斷小球的新位置有無超出墻壁,如果超出則進行速度修正讓小球反彈。
第二個方法里的一些常量ballRadius =30, g = 9.8 , mocali = 0.5,balls = [],collarg = 0.8,pxpm = canvas.width/20; 意思很明顯:ballradius是球半徑,g是重力加速度,mocali是空氣阻力引起的水平方向的減速度,balls是一個用于存放小球?qū)ο蟮臄?shù)組,collarg是彈力系數(shù)。pxpm是像素與米之間的映射,把畫布當成是20米寬的區(qū)域。
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。
新聞熱點
疑難解答