03壁に当たるたびに力を失う反発係数の壁バウンドボール
画面端に触れた瞬間に方向を反転させ、その速度に反発係数を掛けて弱めることで、跳ねるたびにボールの動きが少しずつ収まっていく。
使いどころ閉じたキャンバス内で長く動き続ける背景シーン
KICK_SPEEDMIN_SPEEDkick

<main class="stage">
<div class="bp is-demo" id="bpRoot">
<canvas class="bp__canvas" id="bpCanvas" width="480" height="300"></canvas>
<p class="bp__caption">画面の端に触れた瞬間に向きを反転させ、その速度に反発係数を掛けて減らすことで、跳ねるたびにボールの動きが少しずつ収まっていく。</p>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
@include stage($stage-orange);
.bp {
position: relative;
width: min(92vw, calc(160vh - 12.8vw));
aspect-ratio: 480 / 300;
margin: 0 auto;
border-radius: $r-card;
overflow: hidden;
box-shadow: $shadow-raised;
background: $stage-orange;
}
.bp__canvas {
display: block;
width: 100%;
height: 100%;
}
.bp__caption {
position: absolute;
left: $sp-3;
bottom: $sp-3;
max-width: 80%;
margin: 0;
padding: $sp-1 $sp-3;
border-radius: $r-pill;
background: rgba(255, 255, 255, .85);
color: $subject-ink;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
pointer-events: none;
}
@media (max-width: 340px) {
.bp__caption { font-size: 10px; padding: $sp-1 $sp-2; }
}
@media (prefers-reduced-motion: reduce) {
.bp { cursor: default; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ff4d1f;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.bp {
position: relative;
width: min(92vw, 160vh - 12.8vw);
aspect-ratio: 480/300;
margin: 0 auto;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
background: #ff4d1f;
}
.bp__canvas {
display: block;
width: 100%;
height: 100%;
}
.bp__caption {
position: absolute;
left: 12px;
bottom: 12px;
max-width: 80%;
margin: 0;
padding: 4px 12px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.85);
color: #17141a;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
pointer-events: none;
}
@media (max-width: 340px) {
.bp__caption {
font-size: 10px;
padding: 4px 8px;
}
}
@media (prefers-reduced-motion: reduce) {
.bp {
cursor: default;
}
}(function () {
// 기법: 공이 캔버스 네 변 중 하나에 닿으면 그 축의 속도 부호를 뒤집고 WALL_RESTITUTION
// 을 곱해 줄인다 — 반복할수록 속도 크기가 기하급수로 잦아든다. 전체 속도가 MIN_SPEED
// 아래로 내려가면 씨드 난수로 새 방향·속도를 받아 다시 살아난다(같은 감쇠 패턴을
// 반복해서 보여주기 위함이지 에너지가 새로 생기는 건 아니다).
var root = document.getElementById('bpRoot');
var canvas = document.getElementById('bpCanvas');
var ctx = canvas.getContext('2d');
var wrap = canvas.parentElement;
var CALC_W = 320, CALC_H = 200;
var WALL_RESTITUTION = 0.86;
var MIN_SPEED = 46;
var KICK_SPEED = 210;
var STAGE_BG = '255,77,31';
function seedRand(seed) {
var s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
var rand = seedRand(427031);
var COLORS = ['#b9a0ff', '#6ec8ff', '#ff9ebb'];
var radii = [11, 15, 19];
var balls = [];
function kick(b) {
var ang = rand() * Math.PI * 2;
var spd = KICK_SPEED * (0.7 + rand() * 0.5);
b.vx = Math.cos(ang) * spd;
b.vy = Math.sin(ang) * spd;
b.hits = 0;
}
for (var i = 0; i < radii.length; i += 1) {
var r = radii[i];
var b = { x: r + rand() * (CALC_W - r * 2), y: r + rand() * (CALC_H - r * 2), r: r, color: COLORS[i], squash: 0, hits: 0 };
kick(b);
balls.push(b);
}
function stepSim(dtMs) {
var dtS = dtMs / 1000;
for (var i = 0; i < balls.length; i += 1) {
var b = balls[i];
b.x += b.vx * dtS;
b.y += b.vy * dtS;
var hit = false;
if (b.x - b.r < 0) { b.x = b.r; b.vx = -b.vx * WALL_RESTITUTION; hit = true; }
if (b.x + b.r > CALC_W) { b.x = CALC_W - b.r; b.vx = -b.vx * WALL_RESTITUTION; hit = true; }
if (b.y - b.r < 0) { b.y = b.r; b.vy = -b.vy * WALL_RESTITUTION; hit = true; }
if (b.y + b.r > CALC_H) { b.y = CALC_H - b.r; b.vy = -b.vy * WALL_RESTITUTION; hit = true; }
if (hit) {
b.hits += 1;
b.squash = Math.min(1, Math.hypot(b.vx, b.vy) / 260 + 0.25);
}
b.squash = Math.max(0, b.squash - dtS * 3.4);
var speed = Math.hypot(b.vx, b.vy);
if (speed < MIN_SPEED) kick(b);
}
}
function drawBall(sx, sy, b) {
var px = b.x * sx, py = b.y * sy, pr = b.r * ((sx + sy) / 2);
var ang = Math.atan2(b.vy, b.vx);
var speed = Math.hypot(b.vx, b.vy);
var stretch = 1 + Math.min(0.4, speed / 900);
ctx.save();
ctx.translate(px, py);
ctx.rotate(ang);
ctx.scale(stretch, (1 - b.squash * 0.3) / stretch);
ctx.beginPath();
ctx.arc(0, 0, pr, 0, Math.PI * 2);
ctx.fillStyle = b.color;
ctx.fill();
ctx.restore();
}
function draw() {
var sx = cw / CALC_W, sy = ch / CALC_H;
ctx.fillStyle = 'rgba(' + STAGE_BG + ',0.24)';
ctx.fillRect(0, 0, cw, ch);
ctx.strokeStyle = 'rgba(255,255,255,0.35)';
ctx.lineWidth = 2;
ctx.strokeRect(2, 2, cw - 4, ch - 4);
for (var j = 0; j < balls.length; j += 1) drawBall(sx, sy, balls[j]);
}
var cw = 480, ch = 300;
function fit() {
var r = wrap.getBoundingClientRect();
cw = Math.max(1, Math.round(r.width));
ch = Math.max(1, Math.round(r.height));
canvas.width = cw; canvas.height = ch;
ctx.fillStyle = 'rgb(' + STAGE_BG + ')';
ctx.fillRect(0, 0, cw, ch);
draw();
}
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var elapsed = 0;
if (reduce) root.classList.remove('is-demo');
var warmSteps = reduce ? 50 : 40;
for (var w = 0; w < warmSteps; w += 1) { elapsed += 16; stepSim(16); }
var lastTs = null;
var acc = 0;
var FIXED_DT = 16;
function tick(ts) {
if (lastTs === null) lastTs = ts;
var frameDt = Math.min(ts - lastTs, 48);
lastTs = ts;
if (!reduce) {
acc += frameDt;
while (acc >= FIXED_DT) { elapsed += FIXED_DT; stepSim(FIXED_DT); acc -= FIXED_DT; }
draw();
}
requestAnimationFrame(tick);
}
fit();
window.addEventListener('resize', fit);
draw();
requestAnimationFrame(tick);
})();import { useEffect, useRef } from "react";
import styles from "./BallPhysicsWallRestitutionBounce.module.scss";
type Ball = { x: number; y: number; vx: number; vy: number; r: number; color: string; squash: number; hits: number };
export default function BallPhysicsWallRestitutionBounce() {
const rootRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const root = rootRef.current;
const canvas = canvasRef.current;
if (!root || !canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const wrap = canvas.parentElement as HTMLElement;
const CALC_W = 320, CALC_H = 200;
const WALL_RESTITUTION = 0.86;
const MIN_SPEED = 46;
const KICK_SPEED = 210;
const STAGE_BG = "255,77,31";
function seedRand(seed: number) {
let s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
const rand = seedRand(427031);
const COLORS = ["#b9a0ff", "#6ec8ff", "#ff9ebb"];
const radii = [11, 15, 19];
const balls: Ball[] = [];
function kick(b: Ball) {
const ang = rand() * Math.PI * 2;
const spd = KICK_SPEED * (0.7 + rand() * 0.5);
b.vx = Math.cos(ang) * spd;
b.vy = Math.sin(ang) * spd;
b.hits = 0;
}
for (let i = 0; i < radii.length; i += 1) {
const r = radii[i];
const b: Ball = { x: r + rand() * (CALC_W - r * 2), y: r + rand() * (CALC_H - r * 2), vx: 0, vy: 0, r, color: COLORS[i], squash: 0, hits: 0 };
kick(b);
balls.push(b);
}
function stepSim(dtMs: number) {
const dtS = dtMs / 1000;
for (const b of balls) {
b.x += b.vx * dtS;
b.y += b.vy * dtS;
let hit = false;
if (b.x - b.r < 0) { b.x = b.r; b.vx = -b.vx * WALL_RESTITUTION; hit = true; }
if (b.x + b.r > CALC_W) { b.x = CALC_W - b.r; b.vx = -b.vx * WALL_RESTITUTION; hit = true; }
if (b.y - b.r < 0) { b.y = b.r; b.vy = -b.vy * WALL_RESTITUTION; hit = true; }
if (b.y + b.r > CALC_H) { b.y = CALC_H - b.r; b.vy = -b.vy * WALL_RESTITUTION; hit = true; }
if (hit) {
b.hits += 1;
b.squash = Math.min(1, Math.hypot(b.vx, b.vy) / 260 + 0.25);
}
b.squash = Math.max(0, b.squash - dtS * 3.4);
const speed = Math.hypot(b.vx, b.vy);
if (speed < MIN_SPEED) kick(b);
}
}
let cw = 480, ch = 300;
function drawBall(sx: number, sy: number, b: Ball) {
const px = b.x * sx, py = b.y * sy, pr = b.r * ((sx + sy) / 2);
const ang = Math.atan2(b.vy, b.vx);
const speed = Math.hypot(b.vx, b.vy);
const stretch = 1 + Math.min(0.4, speed / 900);
ctx!.save();
ctx!.translate(px, py);
ctx!.rotate(ang);
ctx!.scale(stretch, (1 - b.squash * 0.3) / stretch);
ctx!.beginPath();
ctx!.arc(0, 0, pr, 0, Math.PI * 2);
ctx!.fillStyle = b.color;
ctx!.fill();
ctx!.restore();
}
function draw() {
const sx = cw / CALC_W, sy = ch / CALC_H;
ctx!.fillStyle = "rgba(" + STAGE_BG + ",0.24)";
ctx!.fillRect(0, 0, cw, ch);
ctx!.strokeStyle = "rgba(255,255,255,0.35)";
ctx!.lineWidth = 2;
ctx!.strokeRect(2, 2, cw - 4, ch - 4);
for (const b of balls) drawBall(sx, sy, b);
}
function fit() {
const r = wrap.getBoundingClientRect();
cw = Math.max(1, Math.round(r.width));
ch = Math.max(1, Math.round(r.height));
canvas!.width = cw; canvas!.height = ch;
ctx!.fillStyle = "rgb(" + STAGE_BG + ")";
ctx!.fillRect(0, 0, cw, ch);
draw();
}
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let elapsed = 0;
if (reduce) root.classList.remove("is-demo");
const warmSteps = reduce ? 50 : 40;
for (let w = 0; w < warmSteps; w += 1) { elapsed += 16; stepSim(16); }
let lastTs: number | null = null;
let acc = 0;
const FIXED_DT = 16;
let raf = 0;
function tick(ts: number) {
if (lastTs === null) lastTs = ts;
const frameDt = Math.min(ts - lastTs, 48);
lastTs = ts;
if (!reduce) {
acc += frameDt;
while (acc >= FIXED_DT) { elapsed += FIXED_DT; stepSim(FIXED_DT); acc -= FIXED_DT; }
draw();
}
raf = requestAnimationFrame(tick);
}
fit();
window.addEventListener("resize", fit);
draw();
raf = requestAnimationFrame(tick);
return () => {
cancelAnimationFrame(raf);
window.removeEventListener("resize", fit);
};
}, []);
return (
<main className={styles.stage}>
<div className={`${styles.bp} is-demo`} ref={rootRef}>
<canvas className={styles.bp__canvas} ref={canvasRef} width={480} height={300} />
<p className={styles.bp__caption}>화면 가장자리에 닿는 순간 방향을 반대로 뒤집고 그 속도에 반발계수를 곱해 줄여, 튕길수록 공의 움직임이 조금씩 잦아든다</p>
</div>
</main>
);
}03 壁に当たるたびに力を失う反発係数の壁バウンドボール — 計測 累積面積 35.015% · 動いたフレーム 23/23GODRICH オリジナル · SCSS と React は zip に同梱 · 跳ねるボール アニメーション 9選 — 衝突と重力の物理計算
このデモが属する記事
跳ねるボール アニメーション 9選 — 衝突と重力の物理計算跳ねるボール アニメーションを9パターンまとめました。01番のボールは反発係数0.82で速度を交換し、04番のボールは同じ係数でも質量が違うと跳ね返る高さが変わり、05番のボールはポインターが近づくとその係数の代わりに反発力を受けて散らばる この記事のデモをすべて見る


