話說這只是一個簡單的DEMO。游戲性,游戲規則什么的我都沒怎么考慮,如果有興趣細化的朋友可以細化一下,比如細化一下規則,游戲開關,加個聲音,細化一下進球檢測,更嚴謹甚至可以去查下擊球力度、桌面真實摩擦力等來把游戲弄的更像游戲。我只是給個編程思路哈,隨便坐個DEMO而已,玩起來估計還是不會很爽快的~~
桌球游戲
整個桌球游戲就兩個類,一個是球,一個是輔助瞄準線。如果想把改游戲弄的更復雜,還可以再抽象一個形狀類,用于檢測球與邊角的碰撞以及進球。我做的這個游戲采取了最簡單的墻壁碰撞檢測,所以沒有進行球與不規則形狀的碰撞檢測,如果想玩更復雜的碰撞,可以戳 關于簡單的碰撞檢測 岑安大大講的還是很好的。好,接下來就一步一步來:
【球】
先貼代碼:
[/code]var Ball = function(x , y , ismine){
this.x = x;
this.y = y;
this.ismine = ismine;
this.oldx = x;
this.oldy = y;
this.vx = 0;
this.vy = 0;
this.radius = ballRadius;
this.inhole = false;this.moving = true;
}
Ball.prototype = {
constructor:Ball,
_paint:function(){
var b = this.ismine?document.getElementById("wb") : document.getElementById("yb")
if(b.complete) {
ctx.drawImage(b , this.x-this.radius , this.y-this.radius , 2*this.radius , 2*this.radius);
}
else {
b.onload = function(){
ctx.drawImage(b , this.x-this.radius , this.y-this.radius , 2*this.radius , 2*this.radius);
}
}
},
_run:function(t){
this.oldx = this.x;
this.oldy = this.y;
this.vx = Math.abs(this.vx)<0.1? 0 : (this.vx>0? this.vx-mcl*t : this.vx+mcl*t);
this.vy = Math.abs(this.vy)<0.1? 0 : (this.vy>0? this.vy-mcl*t : this.vy+mcl*t);
// this.vx += this.vx>0? -mcl*t : mcl*t;
// this.vy += this.vy>0? -mcl*t : mcl*t;
this.x += t * this.vx * pxpm;
this.y += t * this.vy * pxpm;
if((this.x<50 && this.y<50) || (this.x>370 && this.x<430 && this.y<50) || (this.x > 758 && this.y<50) || (this.x<46 && this.y>490) || (this.x>377 && this.x<420 && this.y>490) || (this.x > 758 && this.y>490)){
this.inhole = true;
if(this.ismine){
var that = this;
setTimeout(function(){
that.x = 202;
that.y = canvas.height/2;
that.vx = 0;
that.vy = 0;
that.inhole = false;
} , 500)
}
else {
document.getElementById("shotNum").innerHTML = parseInt(document.getElementById("shotNum").innerHTML)+1
}
}
else {
if(this.y > canvas.height - (ballRadius+tbw) || this.y < (ballRadius+tbw)){
this.y = this.y < (ballRadius+tbw) ? (ballRadius+tbw) : (canvas.height - (ballRadius+tbw));
this.derectionY = !this.derectionY;
this.vy = -this.vy*0.6;
}
if(this.x > canvas.width - (ballRadius+tbw) || this.x < (ballRadius+tbw)){
this.x = this.x < (ballRadius+tbw) ? (ballRadius+tbw) : (canvas.width - (ballRadius+tbw));
this.derectionX = !this.derectionX;
this.vx = -this.vx*0.6;
}
}
this._paint();
if(Math.abs(this.vx)<0.1 && Math.abs(this.vy)<0.1){
this.moving = false;
}
else {
this.moving = true;
}
}
}[/code]
球類的屬性:x,y球的位置,vx,vy球的水平速度以及求得垂直速度,ismine代表是白球還是其他球(不同球在_paint方法中繪制的圖片不一樣),oldx,oldy用于保存球的上一幀位置,不過暫時還沒用上,應該有用吧。_paint方法沒什么好說的,_run方法就是跟蹤小球位置,根據小球每一幀的時間來算出小球的位移增量以及速度增量,mcl和pxpm都是常量,mcl是摩擦力,pxpm是大概算個像素和現實轉換比例。。。。然后就是碰撞檢測,這個很容易理解了,就計算小球的位置有沒有超過邊界,超過了就反彈。不過這種碰撞檢測很不嚴謹,如果真要做游戲建議用更復雜一些的。還有就是根據小球的速度來讓小球靜止。
新聞熱點
疑難解答