DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5教程
HTML5 彈跳球實作:從碰撞偵測談起
編輯:HTML5教程     

彈跳球是入門 Canvas 遊戲很好的一道練習題。看似簡單,但裡面藏著座標系、速度向量、邊界碰撞與重繪時機幾個基本觀念,把它寫通,後續做磚塊、打靶之類的遊戲都會順手很多。

先定義世界:箱子與球

程式的開頭先把場景參數寫清楚。要注意一個容易搞混的點:球的座標指的是球心,而不是左上角。因此計算邊界時必須把半徑扣掉,否則球會有一半跑出牆外才反彈。

// 箱子
var box_x=0, box_y=0;
var box_width=300, box_height=300;
// 球(球心定位)
var ball_x=10, ball_y=10;
var ball_radius=10;
var ball_vx=5, ball_vy=3;      // 速度向量
// 有效活動範圍=箱子邊界各減一個半徑
var box_bound_left   = box_x + ball_radius;
var box_bound_right  = box_x + box_width  - ball_radius;
var box_bound_top    = box_y + ball_radius;
var box_bound_bottom = box_y + box_height - ball_radius;
var ctx;

初始化與主迴圈

載入時取得 2D context,設定線寬與填色,然後用 setInterval 每 100 毫秒推進一格。這裡用固定間隔而非 requestAnimationFrame,好處是邏輯簡單、行為可預期;缺點是幀率與螢幕更新不同步,正式專案建議改用 requestAnimationFrame。

function init() {
  ctx = document.getElementById('canvas').getContext('2d');
  ctx.lineWidth = ball_radius;
  ctx.fillStyle = "rgb(200,0,50)";
  move_ball();
  setInterval(move_ball, 100);
}

碰撞偵測:只要反轉速度

每次移動前先算「下一個位置」,逐一檢查是否越界。若越界,就把該軸的速度取負號,並把座標夾回邊界上,避免球貼著牆邊來回抖動。

function move_and_check() {
  var cur_ball_x = ball_x + ball_vx;
  var cur_ball_y = ball_y + ball_vy;
  if (cur_ball_x < box_bound_left)  { ball_vx = -ball_vx; cur_ball_x = box_bound_left; }
  if (cur_ball_x > box_bound_right) { ball_vx = -ball_vx; cur_ball_x = box_bound_right; }
  if (cur_ball_y < box_bound_top)   { ball_vy = -ball_vy; cur_ball_y = box_bound_top; }
  if (cur_ball_y > box_bound_bottom){ ball_vy = -ball_vy; cur_ball_y = box_bound_bottom; }
  ball_x = cur_ball_x;
  ball_y = cur_ball_y;
}

重繪的順序很重要

每一幀的繪製流程是:先清空整個區域,再更新位置,然後畫球,最後畫框線。順序調動就會出現殘影。

function move_ball() {
  ctx.clearRect(box_x, box_y, box_width, box_height);
  move_and_check();
  ctx.beginPath();
  ctx.arc(ball_x, ball_y, ball_radius, 0, Math.PI*2, true);
  ctx.fill();
  ctx.strokeRect(box_x, box_y, box_width, box_height);
}

完整頁面

<html>
<head>
<meta charset=utf-8>
<title>跳跳球</title>
<script>
/* 上述 box、ball 變數與 init、move_ball、move_and_check 皆置於此 */
</script>
</head>
<body onLoad="init()">
<canvas id="canvas" width="400" height="400"/>
</body>
</html>

可以再玩的地方

想讓它更有趣,可以從幾個方向下手:改變 ball_vx 與 ball_vy 的相對大小讓角度不再呆板;加入重力讓 ball_vy 每幀遞增,模擬真實落地;或在碰撞時依入射角做向量反射,取代單純取負號。這些改動都不需要動到主結構,是理解向量運算很好的起點。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved