學 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;
}
小球的屬性很簡單:x、y 是小球的坐標,vx 和 vy 是初始水平速度與垂直速度,radius 是半徑,color 是顏色(為了區分不同球),oldx 和 oldy 則記錄小球上一幀的位置。
屬性寫好後,就在原型中寫小球的動作:
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;
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,分別代表球半徑、重力加速度、空氣阻力引起的水平減速度、存放小球物件的陣列、彈力係數,以及像素與米之間的映射(把畫布當成 20 米寬的區域)。
建立好小球物件後,就開始寫碰撞——小球與小球之間的碰撞:
function collision(){
for(var i=0;i<balls.length;i++){
for(var j=0;j<balls.length;j++){
var b1 = balls[i],b2 = balls[j];
if(b1 !== b2){
var rc = Math.sqrt(Math.pow(b1.x - b2.x , 2) + Math.pow(b1.y - b2.y , 2));
if(Math.ceil(rc) < (b1.radius + b2.radius)){
//獲得碰撞後速度的增量
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 方法,動畫就完成了。