有了上個(gè)物理實(shí)驗(yàn)SuperBall開發(fā)總結(jié)(二)-讓小球動(dòng)起來,其實(shí)就真正明白了這個(gè)游戲的整體框架。
以后的工作就是豐富render(), checkHit()和update(),當(dāng)然當(dāng)代碼量逐漸增多時(shí),我們還需要將代碼分塊,便于閱讀、擴(kuò)展和維護(hù)。
現(xiàn)在我們要將游戲中玩家控制的木板實(shí)現(xiàn)出來.
完成效果
SuperBall_02-Add_A_BOARD
需要先鼠標(biāo)左鍵點(diǎn)擊一下效果框(Result框),獲取焦點(diǎn)后,才會(huì)將鍵盤事件監(jiān)聽導(dǎo)向木板。
加入木板對(duì)象
var board = {
x : 100,
y : 200 -10,
weight : 4,
height : 5, c
olor : "grey"
}
添加木板渲染代碼
//render the board
context.beginPath();
context.moveTo(board.x, board.y);
context.lineTo(board.x + board.width, board.y);
context.lineWidth = board.weight;
context.strokeStyle = board.color;
context.stroke();
context.closePath();
添加小球碰撞木板的檢測代碼
//check the ball hit the board
if(ball.x >= board.x && ball.x <= board.x + board.width)
if(ball.y >= board.y - board.weight/2 - ball.r){
ball.y = board.y - board.weight/2 - ball.r;
ball.vy *= -1;
}
注意這里判斷標(biāo)準(zhǔn)的細(xì)節(jié),由于木板是用一條線畫出來的,所以木板的長度是board.width而寬度是board.weight
添加鍵盤監(jiān)聽
document.onkeydown = checkKeyDown;
function checkKeyDown(event){
switch (event.keyCode) {
case 37: //left
board.x -= 20;
break;
case 39: //right
board.x += 20;
break;
}
}
別讓木板跑出去
//ensure the board is in the canvas
if(board.x <= 0)
board.x = 0;
if(board.x >= 300 - board.width)
board.x = 300 - board.width;
這里的鍵盤監(jiān)聽函數(shù)主要是捕獲鍵盤點(diǎn)擊的代碼,而向左鍵是37, 向右鍵是39.
SuperBall開發(fā)總結(jié)(四)-BOSS出場