순수 HTML5, Three.js, PixiJS
렌더링 라이브러리에는 래퍼가 필요 없으며 packages/sdk-engines에도 이들을 위한 플러그인 폴더가 없습니다. 브라우저 SDK(window.ZokoGames.SDK)가 이미 통합 그 자체이기 때문입니다. 여러분이 추가할 것은 이를 렌더 루프와 오디오에 연결하는 몇 줄뿐입니다. 같은 패턴이 Three.js, PixiJS, Babylon.js, p5.js, Kaboom, 그리고 순수 <canvas>에서 동작합니다. Phaser는 플러그인이 있는 Phaser 페이지를 사용하세요. "미드게임", "보상형" 같은 용어는 용어집에 있습니다.
어떤 경로를 따를까#
| 여러분이 가진 것 | 시작점 |
|---|---|
| 빌드 단계 없이 순수 JavaScript로 만든 완성된 게임 | html5-minimal 스타터 키트: index.html 하나에 모든 SDK 호출이 주석으로 설명되어 있습니다. 필요한 호출을 복사하세요. |
| 번들링한 TypeScript 게임(Vite, Webpack, esbuild) | html5-vite-ts 스타터 키트: src/zoko-sdk.d.ts(window.ZokoGames.SDK의 타입)와 src/zoko.ts(안전한 래퍼). |
| Three.js, PixiJS, Babylon.js 등 | 이 페이지: 어댑터를 본 다음 사용하는 라이브러리의 탭을 보세요. |
1. SDK를 먼저 불러오기#
코드가 실행될 때 window.ZokoGames가 존재하도록 스크립트를 번들보다 앞에 두세요. URL은 정확히 유지하세요. 업로드 검증기가 이 URL을 찾으며, 번들에 포함된 사본은 경고 대상입니다(sdk_bundled).
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script type="module" src="./main.js"></script>번들러를 쓸 때는 모든 에셋 URL이 상대 경로가 되도록 public base를 상대 경로로 설정하세요(Vite에서는 base: "./"). 기술 요구 사항을 참고하세요.
2. 작은 어댑터#
SDK가 없거나 disabled일 때도 게임이 실행되고, 실패한 호출 하나가 프레임을 깨뜨리지 않도록 SDK를 한 번만 감싸세요. SDK.init()은 절대 reject되지 않습니다. 환경이 disabled이면 다른 모든 호출은 sdkDisabled를 던지며, 어댑터가 이를 삼킵니다.
const SDK = window.ZokoGames?.SDK; // undefined when the script was blocked
let online = false;
export async function startPlatform() {
if (!SDK) return;
await SDK.init();
online = SDK.environment !== "disabled"; // "local", "zokogames" or "disabled"
}
export function call(fn, fallback = null) {
if (!online) return Promise.resolve(fallback);
return Promise.resolve().then(fn).catch((e) => { console.warn("sdk", e.code); return fallback; });
}3. 완전히 동작하는 예제(순수 캔버스)#
init, 미드게임 광고, 보상형 광고, 게임플레이 시작과 중지, 저장과 불러오기, 리더보드 점수, 설정, 오디오 잠금 해제를 다룹니다. 라이브러리별 일시정지 코드는 4절에서 이어집니다.
let running = false, inAd = false;
let audioCtx; // created on the first input (audio unlock)
function setMuted(m) { if (m) audioCtx?.suspend(); else audioCtx?.resume(); } // the portal's mute, applied to your audio
function unlockAudio() {
audioCtx ??= new AudioContext();
setMuted(online && SDK.game.settings.muteAudio); // resumes the context unless the portal has muted the game
removeEventListener("pointerdown", unlockAudio);
removeEventListener("keydown", unlockAudio);
}
addEventListener("pointerdown", unlockAudio); // browsers keep audio suspended until a gesture
addEventListener("keydown", unlockAudio);
// Pause on adStarted; resume on adFinished AND adError. Resolves true only when the ad finished.
function showAd(type) {
if (!online) return Promise.resolve(false);
let finished = false;
let wasRunning = false;
const pause = () => { inAd = true; wasRunning = running; running = false; audioCtx?.suspend(); };
const resume = () => {
if (!inAd) return;
inAd = false; running = wasRunning; // a midgame ad at game over must not restart the loop
if (!SDK.game.settings.muteAudio) audioCtx?.resume();
};
return SDK.ad.requestAd(type, {
adStarted: pause,
adFinished: () => { finished = true; resume(); },
adError: (e) => { console.log("no ad:", e.code); resume(); }, // adCooldown, unfilled, adblock ...
}).then(() => finished, () => { resume(); return false; }); // throws (for example sdkDisabled) instead of adError
}
async function boot() {
await startPlatform();
if (online) {
await call(() => SDK.game.loadingStart());
state.best = Number(SDK.data.getItem("best") ?? "0") || 0; // load: synchronous after init
await loadAssets();
await call(() => SDK.game.loadingStop());
SDK.game.addSettingsChangeListener((s) => { if (!inAd) setMuted(s.muteAudio); }); // an ad in progress keeps the sound off
} else {
await loadAssets();
}
showMenu();
}
function startRound() { // the player takes control: now, not at page load
running = true;
call(() => SDK.game.gameplayStart());
}
async function endRound(score) {
running = false;
call(() => SDK.game.gameplayStop());
if (score > state.best) { // save
state.best = score;
try { if (online) SDK.data.setItem("best", String(score)); } catch (e) { console.warn(e.code); } // dataLimitExceeded
}
await submitScore(score); // leaderboard
await showAd("midgame"); // natural break; then show the results screen
showResults(score);
}
async function onRewardButton() {
if (await showAd("rewarded")) grantReward(); // reward only after adFinished
}
addEventListener("visibilitychange", () => { // a hidden tab is not play time
if (document.hidden && running) call(() => SDK.game.gameplayStop());
else if (!document.hidden && running) call(() => SDK.game.gameplayStart());
});리더보드 호출입니다. 로그인한 플레이어만 순위에 오르며, 보드 규칙을 어기는 점수는 호출이 정상적으로 resolve되더라도 조용히 버려집니다. encryptScore 도우미는 리더보드 페이지에 있습니다. 보드에 암호화 키가 없다면 빈 문자열을 넘기세요.
async function submitScore(score) {
const user = await call(() => SDK.user.getUser());
if (!user) return; // guests are not ranked
const encryptedScore = BOARD_KEY
? await encryptScore(score, BOARD_KEY, user.__dangerousUserId, GAME_ID) // fresh payload per submit
: "";
await call(() => SDK.user.submitScore({ encryptedScore, score }));
}4. 라이브러리별 일시정지, 음소거, 재개#
여러분이 소유한 것, 즉 렌더 루프, 자체 시계, 물리, 오디오를 일시정지하세요. 루프는 가벼운 "일시정지" 화면일 때만 계속 돌아야 합니다. 위의 showAd 도우미는 pause와 resume이 사용하는 라이브러리 자체의 스위치를 호출하게 하면 어떤 라이브러리에서도 동작합니다.
import * as THREE from "three";
const renderer = new THREE.WebGLRenderer({ canvas });
const timer = new THREE.Timer(); // THREE.Clock is deprecated since r183 and logs a warning
let paused = false;
renderer.setAnimationLoop(() => {
if (paused) return;
timer.update();
const dt = Math.min(timer.getDelta(), 0.1); // clamp so a long pause does not teleport anything
world.update(dt);
renderer.render(scene, camera);
});
function setLibMuted(m) { listener.setMasterVolume(m ? 0 : 1); }
function setPaused(p) {
paused = p;
if (!p) timer.reset(); // drop the time spent paused
setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).import { Application } from "pixi.js";
import { sound } from "@pixi/sound"; // PixiJS's audio library; it has its own AudioContext
const app = new Application();
await app.init({ resizeTo: window, resolution: Math.min(devicePixelRatio, 2), autoDensity: true });
document.body.append(app.canvas);
function setLibMuted(m) { if (m) sound.muteAll(); else sound.unmuteAll(); }
function setPaused(p) {
app.ticker[p ? "stop" : "start"]();
if (p) sound.pauseAll(); else sound.resumeAll();
setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).import { Engine, Scene, CreateAudioEngineAsync } from "@babylonjs/core";
const engine = new Engine(canvas, true);
const scene = new Scene(engine);
const audio = await CreateAudioEngineAsync(); // the audio engine unlocks itself on the first input
let paused = false;
// Keep the loop registered while paused: Babylon measures frame time inside it, so a stopped loop
// would hand the scene one huge delta on resume (animations and physics jump).
engine.runRenderLoop(() => { if (!paused) scene.render(); });
function setLibMuted(m) { audio.volume = m ? 0 : 1; }
function setPaused(p) {
paused = p;
if (p) audio.pauseAsync(); else audio.resumeAsync();
setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).let last = 0;
function frame(t) {
if (running) {
update(Math.min((t - last) / 1000, 0.1));
draw();
}
last = t;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
// showAd above already flips `running` and suspends the AudioContext.멀티플레이어, 업적, 구매#
이들에는 어댑터가 필요 없습니다. 같은 call 도우미 뒤에서 SDK.game.room(방 데이터 채널, SDK 1.3.0이며 이전 SDK에서는 undefined), SDK.achievements, SDK.store를 직접 호출하세요. game 모듈, 업적, 게임 내 구매를 참고하세요.
5. 크기 조정#
게임은 크기를 알 수 없는 프레임 안에 있으며, 이 크기는 전체 화면과 회전에 따라 바뀝니다. 캔버스 크기는 상수가 아니라 창에서 가져오세요.
function resize() {
const mobile = online && SDK.user.systemInfo.device.type === "mobile";
const dpr = Math.min(window.devicePixelRatio, mobile ? 1 : 2);
renderer.setPixelRatio(dpr); // Three.js; PixiJS uses the `resolution` option
renderer.setSize(innerWidth, innerHeight, false);
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
}
addEventListener("resize", resize);
resize();SDK.user.systemInfo는 init() 이후에만, 그리고 SDK가 비활성화되지 않았을 때만 읽으세요(그렇지 않으면 던집니다). 휴대폰에서 devicePixelRatio를 1로 제한하면 메모리 부족을 피할 수 있습니다. 자세한 내용은 최적화 팁과 모바일 가이드에 있습니다.
웹에서 중요한 내보내기 설정#
- 상대 경로만 사용하고,
index.html은 압축 파일의 루트에 두세요. - 일반 파일로 배포하세요. 페이지가 일반 이름으로 요청하므로 에셋 이름을
.br이나.gz로 바꾸지 마세요. 게임 오리진은.br또는.gz접미사를 일치하는Content-Encoding과 함께 서빙하지만, 그 정확한 이름으로 요청할 때만 동작합니다. 초기 다운로드 추정치는 압축하지 않은 크기를 사용합니다. minify와 tree-shaking을 하고 WebP 또는 Basis/KTX2 텍스처를 사용하세요. 한도: 파일 1,500개, 압축 해제 후 250 MB, 초기 다운로드 약 50 MB(모바일은 20 MB). 첫 프레임을 빠르게를 참고하세요. - 오디오 잠금 해제. 위와 같이 포인터 또는 키 이벤트에서
AudioContext를 만들거나 재개하세요. 광고 뒤에 다시 재개하고SDK.game.settings.muteAudio를 따르세요. - 전체 화면. 포털 프레임 바의 전체 화면 버튼(프레임 전체를 전체 화면으로 만듭니다)을 쓰는 것이 좋습니다. 프레임이 전체 화면을 허용하므로
canvas.requestFullscreen()이 입력 이벤트에서 동작하지만, 이것은 캔버스만 전체 화면으로 만듭니다. 경쟁하는 버튼을 추가하지 마세요. - 메모리. 레벨이 언로드될 때 텍스처와 지오메트리를 해제하세요(Three.js에서는
texture.dispose(), PixiJS에서는destroy()). 포털 프레임에서는 스레드와SharedArrayBuffer를 사용할 수 없으므로(cross-origin isolation 헤더를 보내지 않습니다) 이를 요구하는 라이브러리는 피하세요.
로컬 테스트#
폴더를 localhost에서 서빙하세요(아무 정적 서버나 가능하며, 예를 들면 npx http-server . -p 8080). 그러면 SDK가 자체 로컬 모드로 시작합니다. 광고마다 3초짜리 오버레이, 가짜 플레이어, localStorage 클라우드 저장, 테스트 스토어가 제공됩니다. 시도해 볼 것들:
?sdk_debug=true는 모든 호출을 로그로 남기고,?ad_response=unfilled는 광고 실패를 강제하며,?user_response=logged_out은 게스트 경로를 테스트합니다.- 3분 안에 두 번째 미드게임 광고를 요청하면
adCooldown으로 실패합니다. 실제 규칙이므로 게임이 이를 처리해야 합니다. submitScore는 받아들여지지만 눈에 보이는 일은 일어나지 않으며, 로컬 토큰은 서명되지 않습니다.?useLocalSdk=true없이file://이나 다른 호스트에서 게임을 열어disabled경로를 확인하세요. 그래도 게임은 플레이할 수 있어야 합니다.
그다음 미리보기 도구를 열어 로컬 주소를 입력하고 요구 사항 체크리스트가 채워지는 것을 지켜보세요.
라이브러리 게임 체크리스트#
- SDK 스크립트가 게임 스크립트보다 먼저 로드되고 모든 경로가 상대 경로입니다.
-
SDK가undefined이거나SDK.environment가"disabled"일 때도 게임이 실행됩니다. - 렌더 루프, 시계, 오디오가
adStarted에서 일시정지되고adFinished와adError모두에서 재개됩니다. - 보상은
adFinished이후에만 지급됩니다. - 긴 일시정지 뒤에 아무것도 순간이동하지 않도록 시간 델타를 제한합니다.
-
SDK.game.settings.muteAudio가 시작 시와 변경 시에 적용됩니다. -
gameplayStart는 플레이어가 처음 조작할 때,gameplayStop은 게임 오버, 일시정지, 탭이 숨겨졌을 때 호출합니다. - 캔버스가 창에 맞춰 크기가 바뀌고
devicePixelRatio를 제한합니다. - 레벨이 언로드될 때 텍스처와 지오메트리를 해제합니다.
- 미리보기 도구에서 테스트했습니다.