Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ export const SHAPES = {
bouncyChars: ".,'`·:;\"",
} as const;

export const MOTION = {
/** 이 각도(도)만큼 기울이면 중력이 완전히 그 방향을 향한다 */
tiltFullAtDeg: 45,
/** 흔들기로 판정할 가속도 크기 (m/s², 중력 제외) */
shakeAccelThreshold: 18,
/** 흔들기 연속 발동 방지 쿨다운 */
shakeCooldownMs: 500,
/** 흔들기 임펄스 — 물체에 더해지는 속도의 최대 크기 */
shakeKickPx: 14,
/** 글자를 이만큼 쌓은 뒤에 기울기 힌트/권한을 요청한다 (PRD §4.3) */
promptAfterLetters: 5,
} as const;

export const WORLD = {
/** 바닥·벽 두께(px). 두껍게 해야 빠른 물체가 뚫고 나가지 않는다 */
wallThicknessPx: 200,
Expand Down
81 changes: 81 additions & 0 deletions src/lib/motion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// 폰 자체가 컨트롤러 (PRD §4.3).
// - 기울이기: deviceorientation → 중력 벡터가 기울기를 따라간다
// - 흔들기: devicemotion 가속도(중력 제외)가 임계값을 넘으면 전체 임펄스
//
// iOS 13+ 는 사용자 제스처 안에서 requestPermission 을 호출해야 한다.
// 첫 진입이 아니라 글자를 몇 개 쌓은 뒤 힌트 버튼으로 요청하고,
// 거부되어도 나머지 기능은 전부 동작한다 (PRD §4.3).

import { MOTION } from "./constants";

export interface MotionTarget {
setGravity: (x: number, y: number) => void;
shake: () => void;
}

interface PermissionRequestable {
requestPermission?: () => Promise<"granted" | "denied">;
}

function clamp(value: number): number {
return Math.max(-1, Math.min(1, value));
}

function startListening(target: MotionTarget) {
window.addEventListener("deviceorientation", (e) => {
// 세로(portrait) 기준: gamma = 좌우 기울기, beta = 앞뒤 기울기
const gx = clamp((e.gamma ?? 0) / MOTION.tiltFullAtDeg);
const gy = clamp((e.beta ?? 0) / MOTION.tiltFullAtDeg);
target.setGravity(gx, gy);
});

let lastShakeAt = 0;
window.addEventListener("devicemotion", (e) => {
const a = e.acceleration;
if (!a) {
return;
}
const magnitude = Math.hypot(a.x ?? 0, a.y ?? 0, a.z ?? 0);
const now = performance.now();
if (magnitude >= MOTION.shakeAccelThreshold && now - lastShakeAt >= MOTION.shakeCooldownMs) {
lastShakeAt = now;
target.shake();
}
});
}

/** 글자가 어느 정도 쌓인 뒤 한 번만 호출한다 */
export function setupMotion(target: MotionTarget, promptButton: HTMLButtonElement | null) {
if (!("DeviceOrientationEvent" in window)) {
return; // 센서 없는 환경(데스크톱) — 조용히 무시
}

const orientation = DeviceOrientationEvent as unknown as PermissionRequestable;
if (typeof orientation.requestPermission !== "function") {
startListening(target); // 안드로이드 등 — 권한 불필요
return;
}

// iOS — 힌트 버튼을 보여주고, 탭(제스처) 안에서 권한을 요청한다
if (!promptButton) {
return;
}
promptButton.hidden = false;
promptButton.addEventListener(
"click",
async () => {
promptButton.hidden = true;
try {
const motion = DeviceMotionEvent as unknown as PermissionRequestable;
const granted = await orientation.requestPermission?.();
await motion.requestPermission?.().catch(() => "denied");
if (granted === "granted") {
startListening(target);
}
} catch {
// 거부 — 기울기 없이도 나머지는 전부 동작한다
}
},
{ once: true },
);
}
22 changes: 20 additions & 2 deletions src/lib/stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// matter.js 기본 렌더러 대신 캔버스에 글자를 직접 그린다 (PRD §6).
import Matter, { type IChamferableBodyDefinition } from "matter-js";

import { MASS, PHYSICS, RENDER, SHAPES, WORLD } from "./constants";
import { MASS, MOTION, PHYSICS, RENDER, SHAPES, WORLD } from "./constants";

const { Bodies, Body, Composite, Engine } = Matter;

Expand All @@ -22,6 +22,10 @@ export interface StageOptions {
export interface Stage {
/** 글자 하나를 화면 상단 중앙에서 떨어뜨린다 */
spawnLetter: (char: string) => void;
/** 중력 벡터를 바꾼다 (기울기 컨트롤, 각 성분 -1~1) */
setGravity: (x: number, y: number) => void;
/** 전체 물체에 랜덤 임펄스 (흔들기) */
shake: () => void;
}

export function mountStage(canvas: HTMLCanvasElement, options: StageOptions = {}): Stage {
Expand Down Expand Up @@ -204,5 +208,19 @@ export function mountStage(canvas: HTMLCanvasElement, options: StageOptions = {}

requestAnimationFrame(frame);

return { spawnLetter };
function setGravity(x: number, y: number) {
engine.gravity.x = Math.max(-1, Math.min(1, x));
engine.gravity.y = Math.max(-1, Math.min(1, y));
}

function shake() {
for (const { body } of letters) {
Body.setVelocity(body, {
x: body.velocity.x + (Math.random() - 0.5) * 2 * MOTION.shakeKickPx,
y: body.velocity.y - Math.random() * MOTION.shakeKickPx,
});
}
}

return { spawnLetter, setGravity, shake };
}
34 changes: 33 additions & 1 deletion src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,41 @@ const base = import.meta.env.BASE_URL.endsWith("/")
<main id="stage">
<canvas id="stage-canvas"></canvas>
<p id="hint">아무 글자나 쳐 보세요</p>
<button id="motion-hint" hidden>📱 기울여서 무너뜨리기</button>
<input id="letter-input" type="text" placeholder="여기에 입력" aria-label="글자 입력" />
</main>
</body>
</html>

<script>
import { MOTION } from "../lib/constants";
import { keepFocusForDesktop, wireLetterInput } from "../lib/input";
import { setupMotion } from "../lib/motion";
import { mountStage } from "../lib/stage";

const canvas = document.querySelector<HTMLCanvasElement>("#stage-canvas");
const hint = document.querySelector<HTMLParagraphElement>("#hint");
const input = document.querySelector<HTMLInputElement>("#letter-input");
const motionHint = document.querySelector<HTMLButtonElement>("#motion-hint");
if (!canvas || !input) {
throw new Error("#stage-canvas / #letter-input 을 찾지 못했다");
}

const stage = mountStage(canvas, { onFirstSpawn: () => hint?.remove() });

wireLetterInput(input, { onChar: (char) => stage.spawnLetter(char) });
// 글자를 몇 개 쌓은 뒤에 기울기/흔들기를 켠다 (iOS 는 힌트 버튼으로 권한 요청)
let spawnCount = 0;
let motionArmed = false;
wireLetterInput(input, {
onChar: (char) => {
stage.spawnLetter(char);
spawnCount++;
if (!motionArmed && spawnCount >= MOTION.promptAfterLetters) {
motionArmed = true;
setupMotion(stage, motionHint);
}
},
});

// 캔버스를 탭해도 입력 박스로 focus (click 은 신뢰된 제스처라 키보드가 뜬다)
canvas.addEventListener("click", () => input.focus({ preventScroll: true }));
Expand Down Expand Up @@ -106,6 +122,22 @@ const base = import.meta.env.BASE_URL.endsWith("/")
border-color: rgba(255, 255, 255, 0.35);
}

/* 기울기 권한 힌트 — 상단 중앙, 탭하면 iOS 권한 요청 */
#motion-hint {
position: fixed;
top: calc(env(safe-area-inset-top, 0px) + 16px);
left: 50%;
transform: translateX(-50%);
padding: 8px 16px;
font-size: 14px;
color: #e8e8ef;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 999px;
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
}

#hint {
position: absolute;
inset: 0;
Expand Down
Loading