物體以一定的初速度沿水平方向拋出,若僅受重力作用,這樣的運動稱為平拋運動。它可以拆解為兩個互相獨立的分運動:水平方向的等速直線運動,加上垂直方向的自由落體運動。
因為所受合外力為恆力,平拋運動屬於恆定加速度的曲線運動,軌跡是一條拋物線。兩個關鍵結論值得記住:
模擬的核心只有一件事:每一幀讓水平速度保持不變,同時讓垂直速度累加重力加速度。碰撞時再依能量衰減係數打折,模擬反彈逐漸減弱的效果。
<Html>
<head>
<meta charset="utf-8">
<title>HTML5 炮彈</title>
<script>
// box
var box_x = 0;
var box_y = 0;
var box_width = 300;
var box_height = 300;
// ball
var ball_x = 10;
var ball_y = 10;
var ball_radius = 10;
var ball_vx = 10;
var ball_vy = 0;
// constant
var g = 10; // 重力加速度
var rate = 0.9; // 能量衰減係數
// bound
var bound_left = box_x + ball_radius;
var bound_right = box_x + box_width - ball_radius;
var bound_top = box_y + ball_radius;
var bound_bottom = box_y + box_height - ball_radius;
var ctx;
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_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);
}
function move_and_check()
{
var cur_ball_x = ball_x + ball_vx;
// 垂直方向:先更新速度,再用均速公式算位移
ball_vy = ball_vy + g;
var cur_ball_y = ball_y + ball_vy + g / 2;
if (cur_ball_x < bound_left)
{
cur_ball_x = bound_left;
ball_vx = -ball_vx * rate;
ball_vy = ball_vy * rate;
}
if (cur_ball_x > bound_right)
{
cur_ball_x = bound_right;
ball_vx = -ball_vx * rate;
ball_vy = ball_vy * rate;
}
if (cur_ball_y < bound_top)
{
cur_ball_y = bound_top;
ball_vy = -ball_vy * rate;
ball_vx = ball_vx * rate;
}
if (cur_ball_y > bound_bottom)
{
cur_ball_y = bound_bottom;
ball_vy = -ball_vy * rate;
ball_vx = ball_vx * rate;
}
ball_x = cur_ball_x;
ball_y = cur_ball_y;
}
</script>
</head>
<body onLoad="init()">
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</Html>
垂直位移用 g/2 修正。如果只寫 ball_y + ball_vy,相當於用「更新後的末速度」乘時間,會高估位移;加上 g/2 之後等同於使用平均速度,軌跡才會貼近真正的拋物線。
碰撞時兩個速度都要衰減。撞到左右邊界時水平速度反向打折,垂直速度也同步衰減;撞到上下邊界則反之。這樣模擬出的效果會像真實小球一樣越彈越低、越滾越慢,最後趨於靜止。