<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title><![CDATA[Cinevva Tutorials]]></title>
        <link>https://app.cinevva.com</link>
        <description><![CDATA[Practical tutorials for web game creators.]]></description>
        <lastBuildDate>Wed, 11 Nov 2026 04:30:11 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>scripts/build-rss.mjs</generator>
        <copyright>Copyright 2024-present Cinevva</copyright>
        <item>
            <title><![CDATA[Agentic AI code tools]]></title>
            <link>https://app.cinevva.com/tutorials/agentic-code-tools</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/agentic-code-tools</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Master Claude Code, Cursor, and GitHub Copilot: understand agentic workflows, best practices, and when to use which tool for maximum productivity.]]></description>
            <content:encoded><![CDATA[<h1>Agentic AI code tools</h1>
<p>AI coding assistants have evolved from simple autocomplete to autonomous agents that can plan, edit multiple files, run tests, and create pull requests. This tutorial covers the three major tools: Claude Code, Cursor, and GitHub Copilot.</p>
<h2>1) What makes a tool &quot;agentic&quot;?</h2>
<p>Traditional AI code completion suggests the next few lines. Agentic tools go further:</p>
<table>
<thead>
<tr>
<th>Capability</th>
<th>Autocomplete</th>
<th>Agentic</th>
</tr>
</thead>
<tbody>
<tr>
<td>Scope</td>
<td>Current line/function</td>
<td>Entire codebase</td>
</tr>
<tr>
<td>Planning</td>
<td>None</td>
<td>Multi-step reasoning</td>
</tr>
<tr>
<td>Execution</td>
<td>Suggestions only</td>
<td>Can edit files, run commands</td>
</tr>
<tr>
<td>Context</td>
<td>Current file</td>
<td>Full repo understanding</td>
</tr>
<tr>
<td>Workflow</td>
<td>Reactive</td>
<td>Autonomous task completion</td>
</tr>
</tbody>
</table>
<p>Agentic tools can understand your entire project structure, plan changes across multiple files, execute those changes, run tests, and iterate until the task is complete.</p>
<h2>2) Quick comparison: Claude Code vs Cursor vs Copilot</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Claude Code</th>
<th>Cursor</th>
<th>GitHub Copilot</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Interface</strong></td>
<td>CLI, web, IDE plugins</td>
<td>Full IDE (VS Code fork)</td>
<td>IDE extensions</td>
</tr>
<tr>
<td><strong>Context window</strong></td>
<td>Large (long-context Opus)</td>
<td>Full repo indexing</td>
<td>Smaller, improving</td>
</tr>
<tr>
<td><strong>Multi-file edits</strong></td>
<td>Strong</td>
<td>Excellent</td>
<td>Improving</td>
</tr>
<tr>
<td><strong>Plan mode</strong></td>
<td>Yes</td>
<td>Yes</td>
<td>Yes (newer)</td>
</tr>
<tr>
<td><strong>Pricing</strong></td>
<td>Pro/Max tiers</td>
<td>Credits + subscription</td>
<td>Subscription</td>
</tr>
<tr>
<td><strong>Best for</strong></td>
<td>Architecture, large refactors</td>
<td>Interactive development</td>
<td>Inline coding</td>
</tr>
</tbody>
</table>
<h2>3) Claude Code fundamentals</h2>
<p>Claude Code runs on Opus 4.8 (its current default model) with large context windows. Install and authenticate:</p>
<pre><code class="language-bash"># Install Claude Code (native installer, recommended)
curl -fsSL https://claude.ai/install.sh | bash

# Or via npm (needs Node 18+)
npm install -g @anthropic-ai/claude-code

# Authenticate: run claude and follow the browser prompt
claude

# Start in your project
cd your-project
claude
</code></pre>
<h3>Basic commands</h3>
<pre><code class="language-bash"># Ask about your codebase
claude &quot;How is authentication implemented here?&quot;

# Generate code
claude &quot;Add a rate limiter middleware&quot;

# Multi-file refactor
claude &quot;Rename UserService to AuthService across the codebase&quot;

# Create a PR
claude &quot;Create a PR that adds input validation to all API endpoints&quot;
</code></pre>
<h3>Project configuration</h3>
<p>Put project context in a <code>CLAUDE.md</code> file at your repo root. Claude Code reads it automatically at the start of every session:</p>
<pre><code class="language-markdown"># Project notes

- Language: TypeScript, formatted with Prettier
- Tests: Vitest, in tests/
- Don't touch node_modules/ or dist/
</code></pre>
<p>Machine-readable settings (tool permissions, env vars, hooks) go in <code>.claude/settings.json</code>. For example, to require approval before destructive tools run, configure permissions there.</p>
<h3>Memory and context</h3>
<p>Persistent project context lives in <a href="http://CLAUDE.md">CLAUDE.md</a> files, which Claude Code loads at the start of every session, plus an auto-memory store Claude updates itself based on your corrections and preferences. To give it lasting context, edit <a href="http://CLAUDE.md">CLAUDE.md</a> rather than passing a one-off &quot;Remember:&quot; prompt:</p>
<pre><code class="language-markdown"># CLAUDE.md
This is a monorepo. Shared code lives in packages/.
</code></pre>
<p>Use the <code>/clear</code> command inside a session to reset the working context.</p>
<h2>4) Cursor IDE agentic features</h2>
<p>Cursor is built around agentic workflows. Key features:</p>
<h3>Agent mode</h3>
<p>Press <code>Cmd+Shift+I</code> (Mac) or <code>Ctrl+Shift+I</code> (Windows/Linux) to open Composer in Agent mode:</p>
<pre><code>Agent mode workflow:
1. Describe your task
2. Agent creates a plan
3. You approve or modify
4. Agent executes changes
5. Review and iterate
</code></pre>
<h3>Plan mode</h3>
<p>For complex tasks, explicitly use Plan mode:</p>
<pre><code>@plan Add user authentication with:
- JWT tokens
- Refresh token rotation
- Password hashing with bcrypt
- Rate limiting on login attempts
</code></pre>
<p>The agent will:</p>
<ol>
<li>Research your existing code</li>
<li>Create a detailed implementation plan</li>
<li>Wait for your approval</li>
<li>Execute step-by-step</li>
</ol>
<h3>Context injection</h3>
<p>Use <code>@</code> to add specific context:</p>
<pre><code>@file src/api/auth.ts
@folder src/middleware
@docs https://jwt.io/introduction

Implement JWT verification middleware following these patterns
</code></pre>
<h3>Parallel agents</h3>
<p>Run multiple agents simultaneously on different branches:</p>
<pre><code># In Cursor:
1. Open Command Palette
2. &quot;Cursor: New Agent in Worktree&quot;
3. Each agent works in isolation
4. Compare results side-by-side
</code></pre>
<p>Cursor 3 added an Agents Window (open it with Cmd+Shift+P then &quot;Agents Window&quot;) that runs multiple agents in parallel across local checkouts, git worktrees, and cloud environments. The /worktree command spins each agent into its own isolated git worktree, and /best-of-n runs the same task across several models so you can compare outputs side by side.</p>
<h3>Rules for consistency</h3>
<p>Create <code>.cursor/rules/project.mdc</code>:</p>
<pre><code class="language-markdown"># Project Rules

## Code Style
- Use TypeScript strict mode
- Prefer functional components
- Use named exports, not default

## Testing
- Every feature needs tests
- Use describe/it blocks
- Mock external services

## Security
- Never commit secrets
- Validate all user input
- Use parameterized queries
</code></pre>
<h2>5) GitHub Copilot agentic features</h2>
<p>Copilot has evolved beyond autocomplete:</p>
<h3>Copilot Chat</h3>
<p>Open chat panel and use slash commands:</p>
<pre><code>/explain - Explain selected code
/fix - Fix issues in selection
/tests - Generate tests
/doc - Add documentation
</code></pre>
<h3>Coding agent (issue to pull request)</h3>
<pre><code># On GitHub:
1. Open a GitHub issue
2. Assign it to &quot;Copilot&quot; as the assignee
3. The coding agent works in the background:
   analyzes the issue, edits files, runs tests
4. It opens a pull request for your review
</code></pre>
<p>This is distinct from Copilot's in-IDE agent mode, which works synchronously alongside you in VS Code or JetBrains.</p>
<p>Copilot now splits its autonomous work in two: agent mode runs synchronously inside your IDE (VS Code and JetBrains), deciding which files to edit, running terminal commands, and iterating on errors; the coding agent runs asynchronously in the cloud, taking an assigned issue and delivering a pull request while you work on something else.</p>
<h3>Inline suggestions with context</h3>
<p>Copilot reads your codebase. Help it with comments:</p>
<pre><code class="language-typescript">// Authentication middleware that:
// - Extracts JWT from Authorization header
// - Validates token signature
// - Attaches user to request
// - Returns 401 if invalid
export function authMiddleware(req, res, next) {
  // Copilot generates the implementation
}
</code></pre>
<h2>6) Best practices for all tools</h2>
<h3>Write clear prompts</h3>
<pre><code>❌ Bad: &quot;Fix the bug&quot;

✅ Good: &quot;Fix the null pointer exception in UserService.getById 
when the user doesn't exist. Return null instead of throwing.&quot;

❌ Bad: &quot;Add tests&quot;

✅ Good: &quot;Add unit tests for the CartService covering:
- Adding items to empty cart
- Removing items
- Calculating totals with discounts
- Edge case: negative quantities&quot;
</code></pre>
<h3>Use plan mode for complex tasks</h3>
<pre><code>For any task touching 3+ files, always:

1. Ask for a plan first
2. Review the plan
3. Approve or modify
4. Let the agent execute
5. Review changes before committing
</code></pre>
<h3>Provide architectural context</h3>
<pre><code>Before major work, brief the agent:

&quot;This is a microservices architecture:
- api-gateway: Routes requests
- auth-service: JWT, sessions
- user-service: User CRUD
- notification-service: Email, push

Services communicate via Redis pub/sub.
Database is PostgreSQL with Prisma ORM.&quot;
</code></pre>
<h3>Test-driven development with agents</h3>
<pre><code>1. Write failing test first:
   &quot;Write a test for user registration that expects email validation&quot;

2. Let agent see the failing test:
   &quot;Implement registration to make this test pass&quot;

3. Iterate until green:
   &quot;Fix the remaining test failures&quot;
</code></pre>
<h2>7) Security considerations</h2>
<p>Agentic tools have real power. Set boundaries:</p>
<h3>Approval gates</h3>
<pre><code class="language-json">// .claude/config.json
{
  &quot;safety&quot;: {
    &quot;requireApproval&quot;: [
      &quot;rm&quot;,
      &quot;git push&quot;,
      &quot;npm publish&quot;,
      &quot;database migrations&quot;,
      &quot;env file changes&quot;
    ]
  }
}
</code></pre>
<h3>Sandboxing</h3>
<pre><code class="language-bash"># Run agents in isolated environments
docker run -v $(pwd):/workspace -it claude-sandbox

# Or use git worktrees for isolation
git worktree add ../feature-branch feature-branch
</code></pre>
<h3>Sensitive files</h3>
<pre><code># .cursorignore / .claudeignore
.env
.env.*
secrets/
credentials/
*.pem
*.key
</code></pre>
<h3>Review all changes</h3>
<pre><code class="language-bash"># Before accepting agent changes:
git diff --stat
git diff

# Use interactive staging
git add -p

# Never auto-merge without review
</code></pre>
<h2>8) Workflow patterns that work</h2>
<h3>Pattern 1: Explore, Plan, Execute</h3>
<pre><code>Session 1: &quot;How does the payment system work?&quot;
          → Agent explores, you learn

Session 2: &quot;What would it take to add Stripe?&quot;
          → Agent creates plan

Session 3: &quot;Implement the Stripe integration&quot;
          → Agent executes plan
</code></pre>
<h3>Pattern 2: Parallel exploration</h3>
<pre><code># In Cursor with parallel agents:

Agent 1: &quot;Implement caching with Redis&quot;
Agent 2: &quot;Implement caching with Memcached&quot;
Agent 3: &quot;Implement caching with in-memory LRU&quot;

→ Compare implementations, pick best approach
</code></pre>
<h3>Pattern 3: Incremental migration</h3>
<pre><code>Step 1: &quot;Identify all uses of deprecated API&quot;
Step 2: &quot;Create adapter for new API&quot;
Step 3: &quot;Migrate module A to use adapter&quot;
Step 4: &quot;Migrate module B...&quot;
...
Step N: &quot;Remove adapter, use new API directly&quot;
</code></pre>
<h3>Pattern 4: Test-first feature development</h3>
<pre><code>1. &quot;Write acceptance tests for user profile editing&quot;
2. &quot;Write unit tests for profile validation&quot;
3. &quot;Implement to pass the tests&quot;
4. &quot;Add integration tests&quot;
5. &quot;Refactor for clarity&quot;
</code></pre>
<h2>9) When to use which tool</h2>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Recommended Tool</th>
</tr>
</thead>
<tbody>
<tr>
<td>Real-time coding, inline help</td>
<td>GitHub Copilot</td>
</tr>
<tr>
<td>Large refactors, architecture</td>
<td>Claude Code</td>
</tr>
<tr>
<td>Full development session</td>
<td>Cursor</td>
</tr>
<tr>
<td>Quick questions about code</td>
<td>Any chat interface</td>
</tr>
<tr>
<td>Creating PRs from issues</td>
<td>Copilot Workspace</td>
</tr>
<tr>
<td>Complex multi-file changes</td>
<td>Cursor Agent</td>
</tr>
<tr>
<td>API design, documentation</td>
<td>Claude Code</td>
</tr>
<tr>
<td>Learning new codebase</td>
<td>Cursor or Claude Code</td>
</tr>
</tbody>
</table>
<h2>10) Measuring effectiveness</h2>
<p>Track these metrics to evaluate agentic tools:</p>
<pre><code class="language-javascript">const metrics = {
  // Productivity
  suggestionsAccepted: 'percentage of suggestions you kept',
  timeToFeature: 'hours from start to merged PR',
  linesPerHour: 'code velocity (use carefully)',
  
  // Quality
  bugsIntroduced: 'defects traced to AI-generated code',
  testCoverage: 'coverage of AI-generated code',
  reviewChanges: 'how much you modify AI suggestions',
  
  // Cost
  apiCosts: 'monthly spend on AI tools',
  creditsUsed: 'Cursor credits consumed',
  
  // Learning
  newPatternsLearned: 'techniques you picked up from AI',
  codebaseUnderstanding: 'how well AI helped you learn',
}
</code></pre>
<h2>11) Common pitfalls</h2>
<h3>Over-trusting the agent</h3>
<pre><code>❌ Accepting large changes without review
❌ Letting agents run destructive commands
❌ Not understanding the code before shipping

✅ Review every change
✅ Understand what you ship
✅ Use agents as collaborators, not replacements
</code></pre>
<h3>Context pollution</h3>
<pre><code>❌ Huge prompts with irrelevant context
❌ Not clearing context between unrelated tasks
❌ Including generated files in context

✅ Keep prompts focused
✅ Use specific @file references
✅ Exclude build artifacts
</code></pre>
<h3>Prompt ambiguity</h3>
<pre><code>❌ &quot;Make it better&quot;
❌ &quot;Fix the issues&quot;
❌ &quot;Add some tests&quot;

✅ &quot;Reduce time complexity from O(n²) to O(n log n)&quot;
✅ &quot;Handle the null case on line 45 by returning early&quot;
✅ &quot;Add tests for edge cases: empty input, max length, unicode&quot;
</code></pre>
<h2>12) Getting started checklist</h2>
<pre><code class="language-markdown">## Setup Checklist

### Claude Code
- [ ] Install CLI: `npm install -g @anthropic/claude-code`
- [ ] Authenticate: `claude login`
- [ ] Create `.claude/config.json`
- [ ] Add `.claudeignore` for sensitive files

### Cursor
- [ ] Download from cursor.com
- [ ] Import VS Code settings
- [ ] Configure `.cursor/rules/`
- [ ] Learn `Cmd+Shift+I` for Agent mode

### GitHub Copilot
- [ ] Install extension in your IDE
- [ ] Enable Copilot Chat
- [ ] Try Copilot Workspace for issues
- [ ] Configure `.github/copilot-instructions.md`

### All Tools
- [ ] Set up approval gates for destructive operations
- [ ] Create ignore files for secrets
- [ ] Establish review workflow
- [ ] Track metrics from day one
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/web-workers-game-logic">Web Workers for game logic</a></li>
<li><a href="/guides/game-jams-hackathons">Game Jams &amp; Hackathons</a> — AI code tools are changing what's possible in a 48-hour jam</li>
<li><a href="/guides/web-game-engines-comparison">Web Game Engines Comparison</a> — picking an engine that pairs well with AI-assisted workflows</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics and telemetry for web games]]></title>
            <link>https://app.cinevva.com/tutorials/analytics-web-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/analytics-web-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Track what matters in your game: player behavior, performance, errors, and conversions. Make data-driven decisions.]]></description>
            <content:encoded><![CDATA[<h1>Analytics and telemetry for web games</h1>
<p>Analytics help you understand what players do, where they struggle, and what keeps them engaged. This tutorial shows what to track and how.</p>
<h2>1) What to track</h2>
<p><strong>Engagement metrics:</strong></p>
<ul>
<li>Session starts and duration</li>
<li>Levels started and completed</li>
<li>Features used</li>
<li>Retention (return visits)</li>
</ul>
<p><strong>Performance metrics:</strong></p>
<ul>
<li>Load time</li>
<li>Frame rate</li>
<li>Memory usage</li>
<li>Errors and crashes</li>
</ul>
<p><strong>Conversion metrics:</strong></p>
<ul>
<li>Tutorial completion</li>
<li>First purchase</li>
<li>Social shares</li>
</ul>
<h2>2) Simple event tracking</h2>
<pre><code class="language-js">class Analytics {
  constructor(endpoint) {
    this.endpoint = endpoint
    this.sessionId = crypto.randomUUID()
    this.queue = []
    this.flushInterval = 30000 // 30 seconds
    
    setInterval(() =&gt; this.flush(), this.flushInterval)
    // Flush when the page is being hidden, not on beforeunload.
    // beforeunload/unload are unreliable (often don't fire on mobile,
    // and block the back/forward cache). visibilitychange + pagehide
    // are the recommended events for end-of-session sends.
    document.addEventListener('visibilitychange', () =&gt; {
      if (document.visibilityState === 'hidden') this.flush()
    })
    window.addEventListener('pagehide', () =&gt; this.flush())
  }
  
  track(event, data = {}) {
    this.queue.push({
      event,
      data,
      sessionId: this.sessionId,
      timestamp: Date.now(),
      url: location.href,
    })
    
    // Flush immediately for important events
    if (event === 'error' || event === 'purchase') {
      this.flush()
    }
  }
  
  async flush() {
    if (this.queue.length === 0) return
    
    const events = [...this.queue]
    this.queue = []
    
    try {
      await fetch(this.endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ events }),
        keepalive: true, // Important for beforeunload
      })
    } catch {
      // Put events back in queue
      this.queue.unshift(...events)
    }
  }
}

const analytics = new Analytics('/api/analytics')
</code></pre>
<h2>3) Session tracking</h2>
<pre><code class="language-js">// Track session start
analytics.track('session_start', {
  referrer: document.referrer,
  screen: `${screen.width}x${screen.height}`,
  devicePixelRatio: window.devicePixelRatio,
  userAgent: navigator.userAgent,
})

// Track session end
let sessionStart = Date.now()

// Send session_end when the page is hidden, not on beforeunload.
// beforeunload is unreliable on mobile and breaks the bfcache.
function recordSessionEnd() {
  analytics.track('session_end', {
    duration: Date.now() - sessionStart,
  })
}
document.addEventListener('visibilitychange', () =&gt; {
  if (document.visibilityState === 'hidden') recordSessionEnd()
})
window.addEventListener('pagehide', recordSessionEnd)

// Track visibility changes
document.addEventListener('visibilitychange', () =&gt; {
  if (document.hidden) {
    analytics.track('tab_hidden')
  } else {
    analytics.track('tab_visible')
  }
})
</code></pre>
<h2>4) Game-specific events</h2>
<pre><code class="language-js">// Level tracking
function onLevelStart(levelId) {
  analytics.track('level_start', { levelId })
}

function onLevelComplete(levelId, score, time) {
  analytics.track('level_complete', {
    levelId,
    score,
    timeSeconds: time,
  })
}

function onLevelFail(levelId, reason) {
  analytics.track('level_fail', {
    levelId,
    reason, // 'death', 'timeout', 'quit'
  })
}

// Achievement tracking
function onAchievementUnlocked(achievementId) {
  analytics.track('achievement', { achievementId })
}

// Tutorial tracking
function onTutorialStep(step, skipped = false) {
  analytics.track('tutorial', { step, skipped })
}
</code></pre>
<h2>5) Performance monitoring</h2>
<pre><code class="language-js">class PerformanceMonitor {
  constructor(analytics) {
    this.analytics = analytics
    this.frameTimes = []
    this.lastFrame = performance.now()
  }
  
  recordFrame() {
    const now = performance.now()
    this.frameTimes.push(now - this.lastFrame)
    this.lastFrame = now
    
    // Keep last 60 frames
    if (this.frameTimes.length &gt; 60) {
      this.frameTimes.shift()
    }
  }
  
  getAverageFPS() {
    if (this.frameTimes.length === 0) return 0
    const avgFrameTime = this.frameTimes.reduce((a, b) =&gt; a + b) / this.frameTimes.length
    return 1000 / avgFrameTime
  }
  
  reportPerformance() {
    const fps = this.getAverageFPS()
    const memory = performance.memory?.usedJSHeapSize
    
    this.analytics.track('performance', {
      avgFPS: Math.round(fps),
      memoryMB: memory ? Math.round(memory / 1024 / 1024) : null,
    })
  }
}

// Report every minute
const perfMonitor = new PerformanceMonitor(analytics)
setInterval(() =&gt; perfMonitor.reportPerformance(), 60000)
</code></pre>
<h3>Attribute jank with Long Animation Frames</h3>
<p>The FPS counter above tells you <em>when</em> frames are dropping, but not <em>why</em>. The Long Animation Frames API (LoAF), which shipped in Chrome and Edge 123, fills that gap. It flags any frame that takes longer than 50ms and breaks down which scripts caused the delay, so you can attribute jank to specific code instead of guessing.</p>
<pre><code class="language-js">if (PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')) {
  const observer = new PerformanceObserver((list) =&gt; {
    for (const entry of list.getEntries()) {
      analytics.track('long_frame', {
        durationMs: Math.round(entry.duration),
        blockingMs: Math.round(entry.blockingDuration),
        // scripts[] names the source URLs that ate the frame
        scripts: entry.scripts?.map((s) =&gt; s.sourceURL),
      })
    }
  })
  observer.observe({ type: 'long-animation-frame', buffered: true })
}
</code></pre>
<p>LoAF is Chromium-only for now (no Firefox or Safari), so feature-detect before using it and keep the FPS counter as your cross-browser baseline.</p>
<h2>6) Error tracking</h2>
<pre><code class="language-js">window.addEventListener('error', (event) =&gt; {
  analytics.track('error', {
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
    stack: event.error?.stack,
  })
})

window.addEventListener('unhandledrejection', (event) =&gt; {
  analytics.track('error', {
    message: event.reason?.message || String(event.reason),
    type: 'unhandledrejection',
    stack: event.reason?.stack,
  })
})

// Custom error tracking
function trackGameError(context, error) {
  analytics.track('game_error', {
    context,
    message: error.message,
    stack: error.stack,
  })
}
</code></pre>
<h2>7) Load time tracking</h2>
<pre><code class="language-js">// Track initial load
window.addEventListener('load', () =&gt; {
  const timing = performance.timing
  const loadTime = timing.loadEventEnd - timing.navigationStart
  const domReady = timing.domContentLoadedEventEnd - timing.navigationStart
  
  analytics.track('page_load', {
    totalMs: loadTime,
    domReadyMs: domReady,
  })
})

// Track game-specific load phases
async function loadGame() {
  const start = performance.now()
  
  await loadCriticalAssets()
  const criticalTime = performance.now() - start
  
  analytics.track('load_critical', { ms: Math.round(criticalTime) })
  
  await loadGameAssets()
  const totalTime = performance.now() - start
  
  analytics.track('load_complete', { ms: Math.round(totalTime) })
}
</code></pre>
<h2>8) Funnel tracking</h2>
<p>Track player progression through key flows:</p>
<pre><code class="language-js">class FunnelTracker {
  constructor(analytics, funnelName) {
    this.analytics = analytics
    this.funnelName = funnelName
    this.startTime = Date.now()
  }
  
  step(stepName) {
    this.analytics.track('funnel_step', {
      funnel: this.funnelName,
      step: stepName,
      elapsedMs: Date.now() - this.startTime,
    })
  }
  
  complete() {
    this.analytics.track('funnel_complete', {
      funnel: this.funnelName,
      totalMs: Date.now() - this.startTime,
    })
  }
  
  abandon(reason) {
    this.analytics.track('funnel_abandon', {
      funnel: this.funnelName,
      reason,
      elapsedMs: Date.now() - this.startTime,
    })
  }
}

// Usage
const onboarding = new FunnelTracker(analytics, 'onboarding')
onboarding.step('welcome_shown')
// ... player clicks continue
onboarding.step('name_entered')
// ... player completes tutorial
onboarding.complete()
</code></pre>
<h2>9) A/B testing support</h2>
<pre><code class="language-js">class ABTest {
  constructor(testName, variants) {
    this.testName = testName
    this.variants = variants
    
    // Get or assign variant
    const stored = localStorage.getItem(`ab_${testName}`)
    if (stored &amp;&amp; variants.includes(stored)) {
      this.variant = stored
    } else {
      this.variant = variants[Math.floor(Math.random() * variants.length)]
      localStorage.setItem(`ab_${testName}`, this.variant)
    }
    
    // Track assignment
    analytics.track('ab_assignment', {
      test: testName,
      variant: this.variant,
    })
  }
  
  getVariant() {
    return this.variant
  }
  
  trackConversion(metric) {
    analytics.track('ab_conversion', {
      test: this.testName,
      variant: this.variant,
      metric,
    })
  }
}

// Usage
const difficultyTest = new ABTest('difficulty', ['easy', 'normal', 'hard'])
game.difficulty = difficultyTest.getVariant()

// When player completes level
difficultyTest.trackConversion('level_complete')
</code></pre>
<h2>10) Privacy considerations</h2>
<pre><code class="language-js">class PrivacyAwareAnalytics extends Analytics {
  constructor(endpoint) {
    super(endpoint)
    this.enabled = this.checkConsent()
  }
  
  checkConsent() {
    return localStorage.getItem('analytics_consent') === 'true'
  }
  
  setConsent(enabled) {
    localStorage.setItem('analytics_consent', enabled ? 'true' : 'false')
    this.enabled = enabled
    
    if (enabled) {
      this.track('consent_granted')
    }
  }
  
  track(event, data = {}) {
    if (!this.enabled) return
    
    // Strip PII
    const sanitized = { ...data }
    delete sanitized.email
    delete sanitized.name
    delete sanitized.ip
    
    super.track(event, sanitized)
  }
}

// Show consent dialog
function showConsentDialog() {
  const dialog = document.createElement('div')
  dialog.innerHTML = `
    &lt;p&gt;We use analytics to improve the game. Is that okay?&lt;/p&gt;
    &lt;button id=&quot;accept&quot;&gt;Accept&lt;/button&gt;
    &lt;button id=&quot;decline&quot;&gt;Decline&lt;/button&gt;
  `
  document.body.appendChild(dialog)
  
  dialog.querySelector('#accept').onclick = () =&gt; {
    analytics.setConsent(true)
    dialog.remove()
  }
  
  dialog.querySelector('#decline').onclick = () =&gt; {
    analytics.setConsent(false)
    dialog.remove()
  }
}
</code></pre>
<h2>Third-party alternatives</h2>
<p>If you don't want to build your own:</p>
<ul>
<li><strong>Plausible</strong> — Privacy-focused, simple</li>
<li><strong>Amplitude</strong> — Product analytics, funnels</li>
<li><strong>Mixpanel</strong> — Event tracking, user journeys</li>
<li><strong>Sentry</strong> — Error tracking specifically</li>
</ul>
<pre><code class="language-js">// Example: Plausible
const script = document.createElement('script')
script.defer = true
script.dataset.domain = 'yourgame.com'
script.src = 'https://plausible.io/js/plausible.js'
document.head.appendChild(script)

// Track custom events
window.plausible('level_complete', { props: { level: '1' } })
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/indexeddb-game-saves">IndexedDB game saves</a></li>
<li><a href="/creators">For creators</a></li>
<li><a href="/guides/itch-io-launch-guide">How to Launch Your Game on itch.io</a> — <a href="http://itch.io">itch.io</a> analytics and tracking downloads</li>
<li><a href="/guides/steam-next-fest-strategy">Steam Next Fest Strategy</a> — measuring wishlists and demo conversion rates</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://plausible.io/">Plausible Analytics</a> — privacy-friendly, lightweight analytics</li>
<li><a href="https://posthog.com/">PostHog</a> — open-source product analytics with event tracking</li>
<li><a href="https://sentry.io/">Sentry</a> — error monitoring and crash reporting for web apps</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Canvas 2D Game Loop Fundamentals]]></title>
            <link>https://app.cinevva.com/tutorials/canvas-2d-game-loop</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/canvas-2d-game-loop</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Build a solid game loop with Canvas 2D. Covers timing, fixed timestep, input, rendering, and the common mistakes that trip people up.]]></description>
            <content:encoded><![CDATA[<h1>Canvas 2D Game Loop Fundamentals</h1>
<p>The game loop is the heartbeat of your game. It runs continuously, updating game state and drawing frames as fast as the browser allows. Get this right and everything else becomes easier. Get it wrong and you'll chase bugs that only appear on certain machines.</p>
<p><strong>Try it (use arrow keys or WASD):</strong></p>
<GameLoopDemo />
<h2>The Simplest Version</h2>
<p>Here's a game loop stripped to its essentials:</p>
<pre><code class="language-js">const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

function gameLoop() {
  update()
  render()
  requestAnimationFrame(gameLoop)
}

function update() {
  // Game logic here
}

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  // Drawing here
}

gameLoop()
</code></pre>
<p>This works, but it has a problem. The <code>update</code> function doesn't know how much time has passed since the last frame. On a 144Hz monitor, it runs twice as fast as on a 60Hz monitor. Your game physics will behave differently on different machines.</p>
<h2>Delta Time Fixes Frame Rate Issues</h2>
<p>To make your game run at the same speed everywhere, you need to track how much time passed between frames. That's called delta time, usually abbreviated <code>dt</code>.</p>
<pre><code class="language-js">let lastTime = 0

function gameLoop(currentTime) {
  const dt = (currentTime - lastTime) / 1000 // convert to seconds
  lastTime = currentTime
  
  update(dt)
  render()
  
  requestAnimationFrame(gameLoop)
}

function update(dt) {
  player.x += player.speed * dt // now works at any frame rate
}

requestAnimationFrame(gameLoop)
</code></pre>
<p>The <code>requestAnimationFrame</code> callback receives the current timestamp in milliseconds. I divide by 1000 to get seconds because it makes the math easier. A speed of 200 means 200 pixels per second, which is intuitive.</p>
<p>One thing to watch out for: on the first frame, <code>lastTime</code> is 0, so <code>dt</code> will be huge. Some people initialize <code>lastTime</code> with <code>performance.now()</code> before starting the loop, or they skip the first frame's update.</p>
<h2>Why requestAnimationFrame Instead of setInterval</h2>
<p>You might wonder why we use <code>requestAnimationFrame</code> instead of <code>setInterval</code>. There are a few reasons.</p>
<p>First, <code>requestAnimationFrame</code> syncs with the display's refresh rate, so you get smooth animation without tearing. Second, it automatically pauses when the tab is hidden, which saves battery and CPU. Third, the browser can optimize it better.</p>
<p>That pause behavior is usually what you want, but it means your game freezes when the user switches tabs. If you're building a multiplayer game or something that needs to keep running, you'll need a different approach.</p>
<h2>Fixed Timestep for Physics</h2>
<p>Variable delta time works for simple movement, but it causes problems with physics simulations. If a frame takes too long, your character might tunnel through a wall because the collision check missed the moment of impact.</p>
<p>The solution is a fixed timestep. You accumulate time and run physics updates at a fixed rate, regardless of how fast frames are rendering.</p>
<pre><code class="language-js">const FIXED_DT = 1 / 60 // 60 physics updates per second
let accumulator = 0
let lastTime = 0

function gameLoop(currentTime) {
  const frameTime = Math.min((currentTime - lastTime) / 1000, 0.25)
  lastTime = currentTime
  
  accumulator += frameTime
  
  while (accumulator &gt;= FIXED_DT) {
    update(FIXED_DT)
    accumulator -= FIXED_DT
  }
  
  render()
  requestAnimationFrame(gameLoop)
}
</code></pre>
<p>That <code>Math.min(..., 0.25)</code> is important. If the tab was hidden and then comes back, <code>frameTime</code> could be huge. Without the cap, the while loop would run hundreds of updates trying to catch up, freezing the game. Capping at 0.25 seconds means you'll never run more than 15 physics updates per frame.</p>
<h2>Organizing Game State</h2>
<p>As your game grows, you need somewhere to put all the data. I like to use a single object that holds everything:</p>
<pre><code class="language-js">const game = {
  state: 'playing', // 'menu', 'playing', 'paused', 'gameover'
  score: 0,
  player: {
    x: 100,
    y: 100,
    vx: 0,
    vy: 0,
    speed: 200,
    width: 32,
    height: 32,
  },
  entities: [],
}
</code></pre>
<p>This makes it easy to save and load game state, reset when the player dies, and debug by logging <code>game</code> to the console. Some people prefer classes, but a plain object works fine for small to medium games.</p>
<h2>Putting It All Together</h2>
<pre><code class="language-js">const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

const FIXED_DT = 1 / 60
let accumulator = 0
let lastTime = 0

const input = { left: false, right: false, up: false, down: false }

const game = {
  player: { x: 100, y: 100, speed: 200 },
}

function update(dt) {
  const p = game.player
  
  if (input.left) p.x -= p.speed * dt
  if (input.right) p.x += p.speed * dt
  if (input.up) p.y -= p.speed * dt
  if (input.down) p.y += p.speed * dt
  
  // Keep in bounds
  p.x = Math.max(0, Math.min(canvas.width - 32, p.x))
  p.y = Math.max(0, Math.min(canvas.height - 32, p.y))
}

function render() {
  ctx.fillStyle = '#1a1a2e'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  ctx.fillStyle = '#4ade80'
  ctx.fillRect(game.player.x, game.player.y, 32, 32)
}

function gameLoop(currentTime) {
  const frameTime = Math.min((currentTime - lastTime) / 1000, 0.25)
  lastTime = currentTime
  
  accumulator += frameTime
  
  while (accumulator &gt;= FIXED_DT) {
    update(FIXED_DT)
    accumulator -= FIXED_DT
  }
  
  render()
  requestAnimationFrame(gameLoop)
}

// Input handling
window.addEventListener('keydown', (e) =&gt; {
  if (e.code === 'ArrowLeft' || e.code === 'KeyA') input.left = true
  if (e.code === 'ArrowRight' || e.code === 'KeyD') input.right = true
  if (e.code === 'ArrowUp' || e.code === 'KeyW') input.up = true
  if (e.code === 'ArrowDown' || e.code === 'KeyS') input.down = true
})

window.addEventListener('keyup', (e) =&gt; {
  if (e.code === 'ArrowLeft' || e.code === 'KeyA') input.left = false
  if (e.code === 'ArrowRight' || e.code === 'KeyD') input.right = false
  if (e.code === 'ArrowUp' || e.code === 'KeyW') input.up = false
  if (e.code === 'ArrowDown' || e.code === 'KeyS') input.down = false
})

requestAnimationFrame(gameLoop)
</code></pre>
<p>This is a complete, runnable game loop. The player moves with arrow keys or WASD, stays within bounds, and everything runs at a consistent speed regardless of frame rate. You can copy this as a starting point for any Canvas 2D game.</p>
<p>Notice how input handling is separate from the game loop. The event listeners just set flags, and the update function reads those flags. This decoupling is important because keyboard events fire at unpredictable times, and you want your game logic to run at a predictable rate.</p>
<h2>Loading and Drawing Sprites</h2>
<pre><code class="language-js">const sprites = {}

async function loadSprite(name, url) {
  return new Promise((resolve) =&gt; {
    const img = new Image()
    img.onload = () =&gt; {
      sprites[name] = img
      resolve(img)
    }
    img.src = url
  })
}

function drawSprite(name, x, y, width, height) {
  const sprite = sprites[name]
  if (sprite) {
    ctx.drawImage(sprite, x, y, width || sprite.width, height || sprite.height)
  }
}
</code></pre>
<p>Images load asynchronously, so you need to wait for them before starting your game. A common pattern is to load all sprites in a <code>loadAssets</code> function that returns a Promise, then start the game loop only after that resolves.</p>
<p>The <code>drawSprite</code> function checks if the sprite exists before drawing. This prevents errors if you try to draw something that hasn't loaded yet.</p>
<h2>Animated Sprites</h2>
<pre><code class="language-js">class AnimatedSprite {
  constructor(image, frameWidth, frameHeight, frameCount, fps = 10) {
    this.image = image
    this.frameWidth = frameWidth
    this.frameHeight = frameHeight
    this.frameCount = frameCount
    this.frameDuration = 1 / fps
    this.currentFrame = 0
    this.elapsed = 0
  }
  
  update(dt) {
    this.elapsed += dt
    if (this.elapsed &gt;= this.frameDuration) {
      this.currentFrame = (this.currentFrame + 1) % this.frameCount
      this.elapsed = 0
    }
  }
  
  draw(ctx, x, y) {
    ctx.drawImage(
      this.image,
      this.currentFrame * this.frameWidth, 0,
      this.frameWidth, this.frameHeight,
      x, y,
      this.frameWidth, this.frameHeight
    )
  }
}
</code></pre>
<p>This class assumes your sprite sheet has frames laid out horizontally in a single row. Each frame is the same size. The <code>update</code> method advances through frames based on elapsed time, and <code>draw</code> uses the nine-argument version of <code>drawImage</code> to clip out just the current frame.</p>
<p>You'd use it like this:</p>
<pre><code class="language-js">const playerWalk = new AnimatedSprite(walkImage, 32, 32, 4, 12)

// In update:
playerWalk.update(dt)

// In render:
playerWalk.draw(ctx, player.x, player.y)
</code></pre>
<h2>Collision Detection</h2>
<pre><code class="language-js">function rectCollision(a, b) {
  return (
    a.x &lt; b.x + b.width &amp;&amp;
    a.x + a.width &gt; b.x &amp;&amp;
    a.y &lt; b.y + b.height &amp;&amp;
    a.y + a.height &gt; b.y
  )
}

function circleCollision(a, b) {
  const dx = a.x - b.x
  const dy = a.y - b.y
  const distance = Math.sqrt(dx * dx + dy * dy)
  return distance &lt; a.radius + b.radius
}

// In update:
for (const enemy of game.enemies) {
  if (rectCollision(game.player, enemy)) {
    handleCollision(game.player, enemy)
  }
}
</code></pre>
<p>Rectangle collision (also called AABB, for axis-aligned bounding box) is the simplest and fastest option. Use it for most things. Circle collision is better for round objects or when you want collisions to feel more forgiving.</p>
<p>For a small number of entities, checking every pair is fine. If you have hundreds of entities, you'll want spatial partitioning (quadtrees or a grid), but that's a topic for another tutorial.</p>
<h2>A Simple Camera</h2>
<pre><code class="language-js">const camera = {
  x: 0,
  y: 0,
  
  follow(target) {
    this.x = target.x - canvas.width / 2
    this.y = target.y - canvas.height / 2
  }
}

function render() {
  ctx.save()
  ctx.translate(-camera.x, -camera.y)
  
  // Draw world
  drawWorld()
  drawEntities()
  
  ctx.restore()
  
  // Draw UI (not affected by camera)
  drawUI()
}
</code></pre>
<p>The trick is <code>ctx.save()</code> and <code>ctx.restore()</code>. You save the current transform state, apply the camera offset with <code>translate</code>, draw everything in world space, then restore so UI elements aren't affected by the camera.</p>
<p>For smoother camera movement, you can lerp toward the target instead of snapping directly to it. Something like <code>this.x += (targetX - this.x) * 0.1</code> gives you that nice trailing effect.</p>
<h2>Pausing the Game</h2>
<pre><code class="language-js">let paused = false

window.addEventListener('keydown', (e) =&gt; {
  if (e.code === 'Escape') {
    paused = !paused
  }
})

function gameLoop(currentTime) {
  const frameTime = Math.min((currentTime - lastTime) / 1000, 0.25)
  lastTime = currentTime
  
  if (!paused) {
    accumulator += frameTime
    while (accumulator &gt;= FIXED_DT) {
      update(FIXED_DT)
      accumulator -= FIXED_DT
    }
  }
  
  render()
  
  if (paused) {
    renderPauseOverlay()
  }
  
  requestAnimationFrame(gameLoop)
}

function renderPauseOverlay() {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  ctx.fillStyle = '#fff'
  ctx.font = '32px sans-serif'
  ctx.textAlign = 'center'
  ctx.fillText('PAUSED', canvas.width / 2, canvas.height / 2)
}
</code></pre>
<p>The key insight is that you stop accumulating time when paused, but you keep rendering. This way the pause overlay appears immediately and the game stays responsive to the unpause input.</p>
<p>You could extend this pattern to handle multiple game states like menus, cutscenes, and game over screens. Just check the current state and route to different update/render functions.</p>
<h2>Common Mistakes</h2>
<p>A few things I've seen trip people up:</p>
<p><strong>Forgetting to clear the canvas.</strong> If you don't call <code>clearRect</code> at the start of render, you'll draw on top of the previous frame and get smearing.</p>
<p><strong>Not capping delta time.</strong> If someone switches tabs and comes back, a huge delta time can break your physics or cause the game to &quot;catch up&quot; for seconds.</p>
<p><strong>Drawing before images load.</strong> Canvas silently ignores <code>drawImage</code> calls with images that haven't loaded. Your sprites just won't appear, with no error message.</p>
<p><strong>Using <code>setInterval</code> for the loop.</strong> It doesn't sync with the display and doesn't pause when the tab is hidden. Use <code>requestAnimationFrame</code>.</p>
<p><strong>Mixing world and screen coordinates.</strong> When you add a camera, keep track of whether a position is in world space or screen space. Mouse clicks come in screen space and need to be converted.</p>
<h2>What's Next</h2>
<p>This tutorial covers the fundamentals. Once you're comfortable with these patterns, you might want to explore:</p>
<p><a href="/tutorials/responsive-game-canvas">Responsive game canvas</a> for handling different screen sizes and high DPI displays.</p>
<p><a href="/tutorials/game-input-handling">Game input handling</a> for touch controls, gamepads, and more sophisticated input systems.</p>
<p><a href="/tutorials/pixel-art-rendering">Pixel art rendering</a> for crisp pixel graphics without blurring.</p>
<p><a href="/tutorials/game-physics-libraries">Game physics libraries</a> for adding rigid body physics, collisions, and joints to your game loop.</p>
<p>If you're deciding between Canvas 2D, WebGL, and WebGPU for your project, the <a href="/guides/web-games-stack-2026">Web Games Tech Stack in 2026</a> guide breaks down the trade-offs. The <a href="/guides/web-game-engines-comparison">Web Game Engines Comparison</a> covers frameworks that handle the game loop for you.</p>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame">MDN: requestAnimationFrame</a> — browser API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">MDN: Canvas API</a> — full Canvas 2D documentation</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent">MDN: KeyboardEvent</a> — key codes and event properties</li>
<li><a href="https://gafferongames.com/post/fix_your_timestep/">Fix Your Timestep!</a> — Glenn Fiedler's classic article on fixed timestep game loops</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enable Wasm threads (SharedArrayBuffer) with COOP/COEP]]></title>
            <link>https://app.cinevva.com/tutorials/coop-coep-sharedarraybuffer</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/coop-coep-sharedarraybuffer</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[A practical, copy‑paste guide to cross‑origin isolation: required headers, common pitfalls, and server config examples for SharedArrayBuffer / WebAssembly threads. Includes a free checker to test whether any URL is cross-origin isolated.]]></description>
            <content:encoded><![CDATA[<h1>Enable Wasm threads (SharedArrayBuffer) with COOP/COEP</h1>
<p>If your web game (or engine export) uses <strong>WebAssembly threads</strong>, it often relies on <code>SharedArrayBuffer</code>. Modern browsers require <strong>cross-origin isolation</strong> for that.</p>
<p><img src="/img/cross-origin-isolation.svg" alt="Diagram: cross-origin isolation headers"></p>
<h2>1) Quick check: are you isolated?</h2>
<p>Open DevTools and run:</p>
<pre><code class="language-js">self.crossOriginIsolated
</code></pre>
<p>If it’s <code>true</code>, you’re in the right security state for <code>SharedArrayBuffer</code>.</p>
<p>Official reference:</p>
<ul>
<li><code>https://developer.mozilla.org/docs/Web/API/Window/crossOriginIsolated</code></li>
</ul>
<h2>2) The two headers you need</h2>
<p>Serve these response headers on your HTML (and typically across your app):</p>
<pre><code class="language-http">Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
</code></pre>
<p>Official references:</p>
<ul>
<li><code>https://web.dev/articles/why-coop-coep</code></li>
<li><code>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer</code></li>
<li><code>https://developer.chrome.com/blog/enabling-shared-array-buffer/</code></li>
</ul>
<h2>3) The #1 reason it “still doesn’t work”: subresources</h2>
<p>With <code>COEP: require-corp</code>, your page can’t freely embed cross-origin resources anymore.</p>
<p>If you load a cross-origin script/image/worker/video/etc, that resource must opt in via:</p>
<ul>
<li>CORS (<code>Access-Control-Allow-Origin</code>) <strong>or</strong></li>
<li>CORP (<code>Cross-Origin-Resource-Policy</code>)</li>
</ul>
<p>Official reference:</p>
<ul>
<li><code>https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cross-Origin_Resource_Policy</code></li>
</ul>
<h2>4) Copy/paste configs</h2>
<h3>Nginx</h3>
<pre><code class="language-nginx">add_header Cross-Origin-Opener-Policy &quot;same-origin&quot; always;
add_header Cross-Origin-Embedder-Policy &quot;require-corp&quot; always;
</code></pre>
<h3>Node / Express</h3>
<pre><code class="language-js">app.use((req, res, next) =&gt; {
  res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
  res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
  next()
})
</code></pre>
<h3>Cloudflare Pages (<code>_headers</code>)</h3>
<pre><code class="language-txt">/*
  Cross-Origin-Opener-Policy: same-origin
  Cross-Origin-Embedder-Policy: require-corp
</code></pre>
<h2>5) Debugging checklist</h2>
<ul>
<li>Confirm the headers are present on the <strong>document</strong> response in the Network panel.</li>
<li>Check <code>self.crossOriginIsolated</code>.</li>
<li>Look for blocked requests (common DevTools message includes “blocked … by COEP”).</li>
<li>Remove or self-host any third‑party scripts that don’t support CORS/CORP.</li>
</ul>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/guides/web-games-stack-2026">Web games tech stack in 2026</a></li>
<li><a href="/tutorials/web-workers-game-logic">Web Workers for game logic</a> — using Workers that benefit from SharedArrayBuffer</li>
<li><a href="/tutorials/websocket-multiplayer-basics">WebSocket multiplayer basics</a> — multiplayer games that need cross-origin isolation</li>
<li><a href="/tutorials/iframe-embedding-games">Iframe embedding games</a> — how COOP/COEP headers affect iframe embeds</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy">MDN: Cross-Origin-Opener-Policy</a> — COOP header reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy">MDN: Cross-Origin-Embedder-Policy</a> — COEP header reference</li>
<li><a href="https://web.dev/articles/cross-origin-isolation-guide">web.dev: Making your website cross-origin isolated</a> — practical deployment guide</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game input handling (keyboard, mouse, touch, gamepad)]]></title>
            <link>https://app.cinevva.com/tutorials/game-input-handling</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/game-input-handling</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Unified input handling for web games: keyboard, mouse, touch, and gamepad support with practical code patterns.]]></description>
            <content:encoded><![CDATA[<h1>Game Input Handling</h1>
<p>Good input handling makes or breaks a game. Laggy controls, missed inputs, or confusing button mappings frustrate players before they even see your game's content. This tutorial shows how to handle keyboard, mouse, touch, and gamepad in a unified way.</p>
<p><strong>Try it first:</strong></p>
<InputDemo />
<h2>The Input State Pattern</h2>
<p>The naive approach is to react to events directly: when the user presses a key, do something. This causes problems. Events fire at unpredictable times, while your game loop runs at a fixed rate. If you move the player in the keydown handler, movement speed depends on key repeat rate, which varies by OS.</p>
<p>Instead, maintain an input state object that your game loop reads:</p>
<pre><code class="language-js">const input = {
  left: false,
  right: false,
  up: false,
  down: false,
  action: false,
  pointer: { x: 0, y: 0, down: false },
}
</code></pre>
<p>Event handlers set these flags. The game loop reads them. This decoupling makes everything simpler: your update logic doesn't care whether input came from keyboard, touch, or gamepad.</p>
<h2>Keyboard</h2>
<p>Use <code>e.code</code> instead of <code>e.key</code> because it refers to the physical key position. WASD works correctly on non-QWERTY layouts.</p>
<pre><code class="language-js">const keyMap = {
  ArrowLeft: 'left',
  ArrowRight: 'right',
  ArrowUp: 'up',
  ArrowDown: 'down',
  KeyA: 'left',
  KeyD: 'right',
  KeyW: 'up',
  KeyS: 'down',
  Space: 'action',
}

window.addEventListener('keydown', (e) =&gt; {
  const action = keyMap[e.code]
  if (action) {
    input[action] = true
    e.preventDefault()
  }
})

window.addEventListener('keyup', (e) =&gt; {
  const action = keyMap[e.code]
  if (action) input[action] = false
})
</code></pre>
<p>The <code>e.preventDefault()</code> stops arrow keys from scrolling the page. Only call it for keys you're handling.</p>
<h2>Mouse</h2>
<p>Mouse coordinates come in screen space. You need to convert to canvas space:</p>
<pre><code class="language-js">const canvas = document.getElementById('game')

canvas.addEventListener('mousemove', (e) =&gt; {
  const rect = canvas.getBoundingClientRect()
  input.pointer.x = e.clientX - rect.left
  input.pointer.y = e.clientY - rect.top
})

canvas.addEventListener('mousedown', () =&gt; {
  input.pointer.down = true
  input.action = true
})

canvas.addEventListener('mouseup', () =&gt; {
  input.pointer.down = false
  input.action = false
})
</code></pre>
<p>If your canvas is scaled (see the responsive canvas tutorial), you'll need to divide by the scale factor to get game coordinates.</p>
<h2>Touch</h2>
<p>Touch works similarly to mouse, but you need <code>e.preventDefault()</code> to stop the browser from scrolling or zooming:</p>
<pre><code class="language-js">canvas.addEventListener('touchstart', (e) =&gt; {
  e.preventDefault()
  const touch = e.touches[0]
  const rect = canvas.getBoundingClientRect()
  input.pointer.x = touch.clientX - rect.left
  input.pointer.y = touch.clientY - rect.top
  input.pointer.down = true
  input.action = true
}, { passive: false })

canvas.addEventListener('touchmove', (e) =&gt; {
  e.preventDefault()
  const touch = e.touches[0]
  const rect = canvas.getBoundingClientRect()
  input.pointer.x = touch.clientX - rect.left
  input.pointer.y = touch.clientY - rect.top
}, { passive: false })

canvas.addEventListener('touchend', () =&gt; {
  input.pointer.down = false
  input.action = false
})
</code></pre>
<p>The <code>{ passive: false }</code> is required because modern browsers default to passive touch listeners for performance. Without it, <code>preventDefault</code> won't work.</p>
<h2>Virtual D-Pad for Mobile</h2>
<p>For games that need directional controls on mobile, add on-screen buttons:</p>
<pre><code class="language-js">function createVirtualDpad(container) {
  const dpad = document.createElement('div')
  dpad.className = 'virtual-dpad'
  dpad.innerHTML = `
    &lt;button data-dir=&quot;up&quot;&gt;↑&lt;/button&gt;
    &lt;button data-dir=&quot;left&quot;&gt;←&lt;/button&gt;
    &lt;button data-dir=&quot;right&quot;&gt;→&lt;/button&gt;
    &lt;button data-dir=&quot;down&quot;&gt;↓&lt;/button&gt;
  `
  
  dpad.querySelectorAll('button').forEach(btn =&gt; {
    const dir = btn.dataset.dir
    btn.addEventListener('touchstart', (e) =&gt; {
      e.preventDefault()
      input[dir] = true
    })
    btn.addEventListener('touchend', () =&gt; input[dir] = false)
  })
  
  container.appendChild(dpad)
}
</code></pre>
<p>Style these buttons to be large enough for thumbs (at least 44x44 pixels) and position them in the bottom corners.</p>
<h2>Gamepad</h2>
<p>Unlike keyboard and mouse, gamepad state isn't event-driven. You have to poll it every frame:</p>
<pre><code class="language-js">function pollGamepads() {
  const gamepads = navigator.getGamepads()
  const gp = gamepads[0]
  
  if (gp) {
    // D-pad or left stick
    input.left = gp.buttons[14]?.pressed || gp.axes[0] &lt; -0.5
    input.right = gp.buttons[15]?.pressed || gp.axes[0] &gt; 0.5
    input.up = gp.buttons[12]?.pressed || gp.axes[1] &lt; -0.5
    input.down = gp.buttons[13]?.pressed || gp.axes[1] &gt; 0.5
    
    // A button (standard mapping)
    input.action = gp.buttons[0]?.pressed
  }
}
</code></pre>
<p>Call <code>pollGamepads()</code> at the start of your update function. The 0.5 threshold on analog sticks creates a dead zone so small stick movements don't register as input.</p>
<p>You can detect when gamepads connect and disconnect:</p>
<pre><code class="language-js">window.addEventListener('gamepadconnected', (e) =&gt; {
  console.log('Gamepad connected:', e.gamepad.id)
})

window.addEventListener('gamepaddisconnected', (e) =&gt; {
  console.log('Gamepad disconnected:', e.gamepad.id)
})
</code></pre>
<h2>Using Input in Your Game Loop</h2>
<p>Now your update function just reads the input state:</p>
<pre><code class="language-js">function update(dt) {
  pollGamepads()
  
  if (input.left) player.x -= player.speed * dt
  if (input.right) player.x += player.speed * dt
  if (input.up) player.y -= player.speed * dt
  if (input.down) player.y += player.speed * dt
  
  if (input.action &amp;&amp; player.canShoot) {
    player.shoot()
  }
}
</code></pre>
<p>This works regardless of whether input came from keyboard, touch, or gamepad. The game logic doesn't need to know.</p>
<h2>Just Pressed vs Held</h2>
<p>Sometimes you want to detect when a button was just pressed this frame, not whether it's currently held. Jumping is a good example: you want one jump per press, not continuous jumping while the button is held.</p>
<pre><code class="language-js">const inputPrev = { ...input }

function wasJustPressed(action) {
  return input[action] &amp;&amp; !inputPrev[action]
}

function endFrame() {
  Object.assign(inputPrev, input)
}
</code></pre>
<p>Call <code>endFrame()</code> at the end of your update loop. Then use <code>wasJustPressed('action')</code> instead of <code>input.action</code> for one-shot actions.</p>
<h2>Focus Loss</h2>
<p>When the browser window loses focus, keyboard events stop firing. If the player was holding a key, it gets stuck on:</p>
<pre><code class="language-js">window.addEventListener('blur', () =&gt; {
  input.left = input.right = input.up = input.down = input.action = false
})
</code></pre>
<p>Without this, the player keeps moving when they alt-tab away.</p>
<h2>Best Practices</h2>
<p>Support both WASD and arrow keys since players have preferences. Allow rebinding and store the configuration in localStorage. Provide touch controls on mobile devices. Test with real gamepads because Xbox, PlayStation, and generic controllers all behave slightly differently. And always handle focus loss gracefully.</p>
<h2>More Resources</h2>
<p><a href="/tutorials/gamepad-api">Gamepad API deep dive</a> covers advanced gamepad features like vibration and multiple players.</p>
<p><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a> covers touch input in more detail.</p>
<p><a href="/tutorials/pointer-lock-fps">Pointer Lock for FPS games</a> shows how to capture the mouse for first-person controls.</p>
<p><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a> shows the input state pattern integrated into a complete game loop.</p>
<p><a href="/tutorials/websocket-multiplayer-basics">WebSocket multiplayer basics</a> covers syncing input across networked players.</p>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code">MDN: KeyboardEvent.code</a> — physical key values for input mapping</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events">MDN: Pointer events</a> — unified mouse and touch events</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API">MDN: Gamepad API</a> — controller support in the browser</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Touch_events">MDN: Touch events</a> — multi-touch handling on mobile</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game physics for web games]]></title>
            <link>https://app.cinevva.com/tutorials/game-physics-libraries</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/game-physics-libraries</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Compare physics engines for web games: Rapier, Cannon-es, Ammo.js, Matter.js, Planck.js. Performance benchmarks, code examples, and when to use each.]]></description>
            <content:encoded><![CDATA[<h1>Game physics for web games</h1>
<p>Physics simulation brings games to life—falling objects, bouncing balls, ragdolls, vehicles, and destructible environments. This guide covers the major physics libraries available for web games, with real code examples and honest pros/cons.</p>
<h2>At a glance</h2>
<table>
<thead>
<tr>
<th>Engine</th>
<th style="text-align:center">Dimension</th>
<th style="text-align:center">Performance</th>
<th style="text-align:center">Size</th>
<th style="text-align:center">Difficulty</th>
<th style="text-align:center">Soft Bodies</th>
<th style="text-align:center">Vehicles</th>
<th style="text-align:center">CCD</th>
<th style="text-align:center">Determinism</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Rapier</strong></td>
<td style="text-align:center">2D/3D</td>
<td style="text-align:center">⭐⭐⭐⭐⭐</td>
<td style="text-align:center">1.4 MB</td>
<td style="text-align:center">Medium</td>
<td style="text-align:center">—</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
</tr>
<tr>
<td><strong>Cannon-es</strong></td>
<td style="text-align:center">3D</td>
<td style="text-align:center">⭐⭐⭐</td>
<td style="text-align:center">150 KB</td>
<td style="text-align:center">Easy</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
</tr>
<tr>
<td><strong>Ammo.js</strong></td>
<td style="text-align:center">3D</td>
<td style="text-align:center">⭐⭐⭐⭐⭐</td>
<td style="text-align:center">1-2 MB</td>
<td style="text-align:center">Hard</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">⚠️</td>
</tr>
<tr>
<td><strong>Jolt</strong></td>
<td style="text-align:center">3D</td>
<td style="text-align:center">⭐⭐⭐⭐⭐</td>
<td style="text-align:center">—</td>
<td style="text-align:center">Hard</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
</tr>
<tr>
<td><strong>Oimo.js</strong></td>
<td style="text-align:center">3D</td>
<td style="text-align:center">⭐⭐⭐</td>
<td style="text-align:center">100 KB</td>
<td style="text-align:center">Easy</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
</tr>
<tr>
<td><strong>Matter.js</strong></td>
<td style="text-align:center">2D</td>
<td style="text-align:center">⭐⭐⭐</td>
<td style="text-align:center">80 KB</td>
<td style="text-align:center">Easy</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">⚠️</td>
</tr>
<tr>
<td><strong>Planck.js</strong></td>
<td style="text-align:center">2D</td>
<td style="text-align:center">⭐⭐⭐⭐</td>
<td style="text-align:center">120 KB</td>
<td style="text-align:center">Medium</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">⚠️</td>
</tr>
<tr>
<td><strong>p2-es</strong></td>
<td style="text-align:center">2D</td>
<td style="text-align:center">⭐⭐⭐</td>
<td style="text-align:center">100 KB</td>
<td style="text-align:center">Medium</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
</tr>
<tr>
<td><strong>Box2D WASM</strong></td>
<td style="text-align:center">2D</td>
<td style="text-align:center">⭐⭐⭐⭐⭐</td>
<td style="text-align:center">300 KB</td>
<td style="text-align:center">Hard</td>
<td style="text-align:center">—</td>
<td style="text-align:center">—</td>
<td style="text-align:center">✅</td>
<td style="text-align:center">✅</td>
</tr>
</tbody>
</table>
<p><strong>Legend:</strong></p>
<ul>
<li>CCD = Continuous Collision Detection (prevents fast objects tunneling through walls)</li>
<li>⚠️ Determinism = Possible with fixed timestep, but not guaranteed cross-platform</li>
</ul>
<h3>Quick recommendations</h3>
<table>
<thead>
<tr>
<th>Your situation</th>
<th>Best choice</th>
</tr>
</thead>
<tbody>
<tr>
<td>Production 3D game</td>
<td><strong>Rapier</strong> — best performance, modern API, active development</td>
</tr>
<tr>
<td>Learning / prototype</td>
<td><strong>Cannon-es</strong> (3D) or <strong>Matter.js</strong> (2D) — simple APIs, easy debugging</td>
</tr>
<tr>
<td>Vehicle physics</td>
<td><strong>Rapier</strong> or <strong>Ammo.js</strong> — both have ray-cast vehicle controllers</td>
</tr>
<tr>
<td>Soft bodies, cloth, ropes</td>
<td><strong>Ammo.js</strong> or <strong>Jolt (JoltPhysics.js)</strong> — both support cloth and soft bodies; Jolt's WASM port is more actively maintained</td>
</tr>
<tr>
<td>Precise 2D platformer</td>
<td><strong>Planck.js</strong> — Box2D algorithms, deterministic with fixed timestep</td>
</tr>
<tr>
<td>Maximum 2D performance</td>
<td><strong>Box2D WASM</strong> — native speed in browser</td>
</tr>
<tr>
<td>Smallest bundle size</td>
<td><strong>Oimo.js</strong> (3D) or <strong>Matter.js</strong> (2D)</td>
</tr>
</tbody>
</table>
<hr>
<h2>Detailed comparison</h2>
<h3>3D Physics Engines</h3>
<table>
<thead>
<tr>
<th>Engine</th>
<th>Language</th>
<th>Size</th>
<th>Performance</th>
<th>Best for</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Rapier</strong></td>
<td>Rust/WASM</td>
<td>~1.4 MB</td>
<td>Excellent</td>
<td>Production games, complex simulations</td>
</tr>
<tr>
<td><strong>Cannon-es</strong></td>
<td>JavaScript</td>
<td>~150 KB</td>
<td>Good</td>
<td>Prototypes, simple games</td>
</tr>
<tr>
<td><strong>Ammo.js</strong></td>
<td>C++/WASM</td>
<td>~1-2 MB</td>
<td>Excellent</td>
<td>AAA features, soft bodies, vehicles</td>
</tr>
<tr>
<td><strong>Jolt</strong></td>
<td>C++/WASM</td>
<td>WASM</td>
<td>Excellent</td>
<td>AAA features with active maintenance</td>
</tr>
<tr>
<td><strong>Oimo.js</strong></td>
<td>JavaScript</td>
<td>~100 KB</td>
<td>Good</td>
<td>Simple games, quick prototypes</td>
</tr>
</tbody>
</table>
<h3>2D Physics Engines</h3>
<table>
<thead>
<tr>
<th>Engine</th>
<th>Language</th>
<th>Size</th>
<th>Performance</th>
<th>Best for</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Matter.js</strong></td>
<td>JavaScript</td>
<td>~80 KB</td>
<td>Good</td>
<td>Visual games, prototypes</td>
</tr>
<tr>
<td><strong>Planck.js</strong></td>
<td>JavaScript</td>
<td>~120 KB</td>
<td>Good</td>
<td>Platformers, precise physics</td>
</tr>
<tr>
<td><strong>p2-es</strong></td>
<td>JavaScript</td>
<td>~100 KB</td>
<td>Good</td>
<td>Constraints, mechanisms</td>
</tr>
<tr>
<td><strong>Box2D WASM</strong></td>
<td>C++/WASM</td>
<td>~300 KB</td>
<td>Excellent</td>
<td>High body counts</td>
</tr>
</tbody>
</table>
<hr>
<h2>3D Physics Engines</h2>
<h3>Rapier — The modern choice</h3>
<p>Rapier is a Rust physics engine with JavaScript/WASM bindings. It's the most performant option for web games in 2025-2026, with 2-5x speed improvements over its 2024 version.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install @dimforge/rapier3d
# Or with SIMD (faster, requires modern browsers):
npm install @dimforge/rapier3d-simd
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import RAPIER from '@dimforge/rapier3d'

// Initialize (async required for WASM)
await RAPIER.init()

// Create world with gravity
const gravity = { x: 0, y: -9.81, z: 0 }
const world = new RAPIER.World(gravity)

// Create ground (static body)
const groundDesc = RAPIER.RigidBodyDesc.fixed()
const groundBody = world.createRigidBody(groundDesc)
const groundCollider = RAPIER.ColliderDesc.cuboid(50, 0.1, 50)
world.createCollider(groundCollider, groundBody)

// Create falling box (dynamic body)
const boxDesc = RAPIER.RigidBodyDesc.dynamic()
  .setTranslation(0, 10, 0)
const boxBody = world.createRigidBody(boxDesc)
const boxCollider = RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5)
  .setDensity(1.0)
  .setRestitution(0.5)
world.createCollider(boxCollider, boxBody)
</code></pre>
<p><strong>Game loop integration:</strong></p>
<pre><code class="language-js">const FIXED_TIMESTEP = 1 / 60

function physicsStep() {
  world.step()
}

function gameLoop() {
  physicsStep()
  
  // Sync render objects with physics
  const position = boxBody.translation()
  const rotation = boxBody.rotation()
  
  // Update your Three.js/Babylon mesh
  mesh.position.set(position.x, position.y, position.z)
  mesh.quaternion.set(rotation.x, rotation.y, rotation.z, rotation.w)
  
  requestAnimationFrame(gameLoop)
}
</code></pre>
<p><strong>Collision detection:</strong></p>
<pre><code class="language-js">// Event-based collision detection
world.contactPairsWith(boxCollider, (otherCollider) =&gt; {
  console.log('Box is touching:', otherCollider)
})

// Ray casting
const ray = new RAPIER.Ray({ x: 0, y: 10, z: 0 }, { x: 0, y: -1, z: 0 })
const hit = world.castRay(ray, 100, true)
if (hit) {
  const hitPoint = ray.pointAt(hit.timeOfImpact)
  console.log('Hit at:', hitPoint)
}
</code></pre>
<p><strong>Joints:</strong></p>
<pre><code class="language-js">// Create a hinge joint (door)
const jointData = RAPIER.JointData.revolute(
  { x: 0, y: 0, z: 0 },  // Anchor on body1
  { x: -1, y: 0, z: 0 }, // Anchor on body2
  { x: 0, y: 1, z: 0 }   // Rotation axis
)
world.createImpulseJoint(jointData, body1, body2, true)
</code></pre>
<p><strong>Vehicle controller:</strong></p>
<pre><code class="language-js">// Create chassis rigid body
const chassisDesc = RAPIER.RigidBodyDesc.dynamic()
  .setTranslation(0, 2, 0)
const chassis = world.createRigidBody(chassisDesc)
const chassisCollider = RAPIER.ColliderDesc.cuboid(1, 0.5, 2)
  .setDensity(100)
world.createCollider(chassisCollider, chassis)

// Create vehicle controller
const vehicle = world.createVehicleController(chassis)

// Add wheels (front-left, front-right, rear-left, rear-right)
const suspensionRestLength = 0.3
const wheelRadius = 0.4

// Front wheels (steering)
vehicle.addWheel(
  { x: -0.8, y: 0, z: 1.2 },   // Connection point
  { x: 0, y: -1, z: 0 },       // Suspension direction
  { x: -1, y: 0, z: 0 },       // Axle direction
  suspensionRestLength,
  wheelRadius
)
vehicle.addWheel(
  { x: 0.8, y: 0, z: 1.2 },
  { x: 0, y: -1, z: 0 },
  { x: -1, y: 0, z: 0 },
  suspensionRestLength,
  wheelRadius
)

// Rear wheels (drive)
vehicle.addWheel(
  { x: -0.8, y: 0, z: -1.2 },
  { x: 0, y: -1, z: 0 },
  { x: -1, y: 0, z: 0 },
  suspensionRestLength,
  wheelRadius
)
vehicle.addWheel(
  { x: 0.8, y: 0, z: -1.2 },
  { x: 0, y: -1, z: 0 },
  { x: -1, y: 0, z: 0 },
  suspensionRestLength,
  wheelRadius
)

// Configure suspension for all wheels
for (let i = 0; i &lt; 4; i++) {
  vehicle.setWheelSuspensionStiffness(i, 30)
  vehicle.setWheelSuspensionCompression(i, 4.4)
  vehicle.setWheelSuspensionRelaxation(i, 2.3)
  vehicle.setWheelMaxSuspensionTravel(i, 0.5)
  vehicle.setWheelFrictionSlip(i, 2)
}

// In game loop
function updateVehicle(steering, engineForce, brakeForce) {
  // Steering (front wheels only)
  vehicle.setWheelSteering(0, steering)
  vehicle.setWheelSteering(1, steering)
  
  // Engine (rear wheels)
  vehicle.setWheelEngineForce(2, engineForce)
  vehicle.setWheelEngineForce(3, engineForce)
  
  // Brakes (all wheels)
  for (let i = 0; i &lt; 4; i++) {
    vehicle.setWheelBrake(i, brakeForce)
  }
  
  // Update vehicle physics
  vehicle.updateVehicle(world.timestep)
}
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Best performance (WASM + SIMD)</li>
<li>Excellent collision detection accuracy</li>
<li>Cross-platform determinism (same inputs = same outputs)</li>
<li>Active development, modern API</li>
<li>Continuous collision detection (no tunneling)</li>
<li>Character controller and vehicle controller built-in</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>Larger bundle size (~1.4 MB)</li>
<li>Async initialization required</li>
<li>More complex API than pure JS alternatives</li>
<li>WASM debugging can be tricky</li>
</ul>
<hr>
<h3>Cannon-es — Simple and effective</h3>
<p>Cannon-es is the maintained fork of Cannon.js. Pure JavaScript, easy to understand, great for learning and prototypes.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install cannon-es
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import * as CANNON from 'cannon-es'

// Create world
const world = new CANNON.World({
  gravity: new CANNON.Vec3(0, -9.81, 0)
})

// Ground
const groundBody = new CANNON.Body({
  type: CANNON.Body.STATIC,
  shape: new CANNON.Plane()
})
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0)
world.addBody(groundBody)

// Falling sphere
const sphereBody = new CANNON.Body({
  mass: 1,
  shape: new CANNON.Sphere(0.5),
  position: new CANNON.Vec3(0, 10, 0)
})
sphereBody.linearDamping = 0.1
world.addBody(sphereBody)
</code></pre>
<p><strong>Game loop:</strong></p>
<pre><code class="language-js">const TIMESTEP = 1 / 60

function animate() {
  world.step(TIMESTEP)
  
  // Sync with Three.js
  mesh.position.copy(sphereBody.position)
  mesh.quaternion.copy(sphereBody.quaternion)
  
  requestAnimationFrame(animate)
}
</code></pre>
<p><strong>Collision events:</strong></p>
<pre><code class="language-js">sphereBody.addEventListener('collide', (event) =&gt; {
  const contact = event.contact
  const impactVelocity = contact.getImpactVelocityAlongNormal()
  
  if (Math.abs(impactVelocity) &gt; 5) {
    console.log('Hard impact!')
  }
})
</code></pre>
<p><strong>Constraints:</strong></p>
<pre><code class="language-js">// Distance constraint (rope-like)
const constraint = new CANNON.DistanceConstraint(
  bodyA, bodyB, 
  2 // distance
)
world.addConstraint(constraint)

// Hinge constraint
const hinge = new CANNON.HingeConstraint(bodyA, bodyB, {
  pivotA: new CANNON.Vec3(1, 0, 0),
  axisA: new CANNON.Vec3(0, 1, 0),
  pivotB: new CANNON.Vec3(-1, 0, 0),
  axisB: new CANNON.Vec3(0, 1, 0)
})
world.addConstraint(hinge)
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Pure JavaScript, no WASM complexity</li>
<li>Small bundle size (~150 KB)</li>
<li>Easy to learn and debug</li>
<li>Works everywhere</li>
<li>Great Three.js integration</li>
<li>Good documentation</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>Slower than WASM alternatives</li>
<li>Struggles with many bodies (&gt;100)</li>
<li>Limited trimesh support</li>
<li>No built-in CCD (tunneling possible)</li>
<li>Less active development</li>
</ul>
<hr>
<h3>Ammo.js — Full Bullet Physics power</h3>
<p>Ammo.js is the Bullet Physics engine compiled to WebAssembly. Maximum features, including soft bodies, vehicles, and advanced constraints.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install ammo.js
# Or use from CDN
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import Ammo from 'ammo.js'

let physicsWorld

async function initPhysics() {
  await Ammo()
  
  const collisionConfig = new Ammo.btDefaultCollisionConfiguration()
  const dispatcher = new Ammo.btCollisionDispatcher(collisionConfig)
  const broadphase = new Ammo.btDbvtBroadphase()
  const solver = new Ammo.btSequentialImpulseConstraintSolver()
  
  physicsWorld = new Ammo.btDiscreteDynamicsWorld(
    dispatcher, broadphase, solver, collisionConfig
  )
  physicsWorld.setGravity(new Ammo.btVector3(0, -9.81, 0))
}

function createBox(mass, width, height, depth, x, y, z) {
  const transform = new Ammo.btTransform()
  transform.setIdentity()
  transform.setOrigin(new Ammo.btVector3(x, y, z))
  
  const motionState = new Ammo.btDefaultMotionState(transform)
  const shape = new Ammo.btBoxShape(
    new Ammo.btVector3(width / 2, height / 2, depth / 2)
  )
  
  const localInertia = new Ammo.btVector3(0, 0, 0)
  if (mass &gt; 0) {
    shape.calculateLocalInertia(mass, localInertia)
  }
  
  const rbInfo = new Ammo.btRigidBodyConstructionInfo(
    mass, motionState, shape, localInertia
  )
  const body = new Ammo.btRigidBody(rbInfo)
  
  physicsWorld.addRigidBody(body)
  return body
}
</code></pre>
<p><strong>Soft bodies (cloth):</strong></p>
<pre><code class="language-js">function createCloth(width, height, segments) {
  const softBodyHelpers = new Ammo.btSoftBodyHelpers()
  
  const corner00 = new Ammo.btVector3(-width/2, height, 0)
  const corner10 = new Ammo.btVector3(width/2, height, 0)
  const corner01 = new Ammo.btVector3(-width/2, 0, 0)
  const corner11 = new Ammo.btVector3(width/2, 0, 0)
  
  const softBody = softBodyHelpers.CreatePatch(
    physicsWorld.getWorldInfo(),
    corner00, corner10, corner01, corner11,
    segments, segments,
    0, true
  )
  
  const sbConfig = softBody.get_m_cfg()
  sbConfig.set_viterations(10)
  sbConfig.set_piterations(10)
  
  softBody.setTotalMass(0.9, false)
  Ammo.castObject(softBody, Ammo.btCollisionObject)
    .getCollisionShape().setMargin(0.05)
  
  physicsWorld.addSoftBody(softBody, 1, -1)
  return softBody
}
</code></pre>
<p><strong>Vehicle physics:</strong></p>
<pre><code class="language-js">function createVehicle(chassisBody) {
  const tuning = new Ammo.btVehicleTuning()
  const rayCaster = new Ammo.btDefaultVehicleRaycaster(physicsWorld)
  const vehicle = new Ammo.btRaycastVehicle(tuning, chassisBody, rayCaster)
  
  vehicle.setCoordinateSystem(0, 1, 2)
  physicsWorld.addAction(vehicle)
  
  // Add wheels
  const wheelRadius = 0.4
  const wheelWidth = 0.3
  const suspensionRestLength = 0.3
  
  const wheelDirectionCS = new Ammo.btVector3(0, -1, 0)
  const wheelAxleCS = new Ammo.btVector3(-1, 0, 0)
  
  function addWheel(isFront, pos) {
    const wheelInfo = vehicle.addWheel(
      pos, wheelDirectionCS, wheelAxleCS,
      suspensionRestLength, wheelRadius, tuning, isFront
    )
    wheelInfo.set_m_suspensionStiffness(20)
    wheelInfo.set_m_wheelsDampingRelaxation(2.3)
    wheelInfo.set_m_wheelsDampingCompression(4.4)
    wheelInfo.set_m_frictionSlip(1000)
    wheelInfo.set_m_rollInfluence(0.1)
  }
  
  addWheel(true, new Ammo.btVector3(1, 0, 1.5))   // Front left
  addWheel(true, new Ammo.btVector3(-1, 0, 1.5))  // Front right
  addWheel(false, new Ammo.btVector3(1, 0, -1.5)) // Rear left
  addWheel(false, new Ammo.btVector3(-1, 0, -1.5))// Rear right
  
  return vehicle
}
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Most complete feature set</li>
<li>Soft bodies, cloth, ropes</li>
<li>Advanced vehicle physics</li>
<li>Battle-tested (used in many AAA games)</li>
<li>Highly configurable</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>Complex, verbose API</li>
<li>Large bundle size</li>
<li>Memory management required (destroy objects)</li>
<li>Steep learning curve</li>
<li>Documentation scattered</li>
<li>Not cross-platform deterministic (same-device only, with careful config)</li>
</ul>
<hr>
<h3>Jolt — modern AAA-grade 3D physics</h3>
<p>Jolt Physics is the engine behind games like Horizon Forbidden West, and JoltPhysics.js brings it to the browser as a WASM port. It's a strong middle ground between Rapier and Ammo.js: more features than Rapier (soft bodies, cloth, a wheeled vehicle controller) with active maintenance that Ammo.js lacks. The npm package is <code>jolt-physics</code>, and there are ready-made integrations for React Three Fiber (<code>@react-three/jolt</code>) and Babylon.js.</p>
<pre><code class="language-bash">npm install jolt-physics
</code></pre>
<p>Like Rapier, it's async-initialized WASM with a verbose-but-complete API mirroring the C++ interface. Reach for Jolt when you want Bullet-class features (soft bodies, vehicles) but want a maintained, modern codebase rather than Ammo.js.</p>
<hr>
<h3>Oimo.js — Lightweight and fast</h3>
<p>Oimo.js is a lightweight 3D physics engine. Great for simple games where you don't need advanced features.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install oimo
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import * as OIMO from 'oimo'

const world = new OIMO.World({
  timestep: 1/60,
  iterations: 8,
  broadphase: 2, // 1: brute, 2: sweep &amp; prune, 3: volume tree
  worldscale: 1,
  random: true,
  gravity: [0, -9.8, 0]
})

// Create ground
world.add({
  type: 'box',
  size: [100, 1, 100],
  pos: [0, -0.5, 0],
  move: false
})

// Create falling sphere
const sphere = world.add({
  type: 'sphere',
  size: [1],
  pos: [0, 10, 0],
  move: true,
  density: 1,
  friction: 0.4,
  restitution: 0.2
})
</code></pre>
<p><strong>Game loop:</strong></p>
<pre><code class="language-js">function animate() {
  world.step()
  
  // Get position/rotation
  const pos = sphere.getPosition()
  const rot = sphere.getQuaternion()
  
  mesh.position.set(pos.x, pos.y, pos.z)
  mesh.quaternion.set(rot.x, rot.y, rot.z, rot.w)
  
  requestAnimationFrame(animate)
}
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Very small (~100 KB)</li>
<li>Simple API</li>
<li>Good performance for basic scenes</li>
<li>Built-in Babylon.js support</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>Limited shapes (primitives only)</li>
<li>No soft bodies</li>
<li>Sparse documentation</li>
<li>Less active development</li>
<li>Limited joint options</li>
</ul>
<hr>
<h2>2D Physics Engines</h2>
<h3>Matter.js — Beautiful and intuitive</h3>
<p>Matter.js is a feature-rich 2D physics engine with excellent rendering and debug tools.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install matter-js
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import Matter from 'matter-js'

const { Engine, Render, World, Bodies, Runner } = Matter

// Create engine
const engine = Engine.create()

// Create renderer (optional, great for debugging)
const render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 800,
    height: 600,
    wireframes: false
  }
})

// Create bodies
const ground = Bodies.rectangle(400, 580, 810, 60, { 
  isStatic: true 
})

const box = Bodies.rectangle(400, 200, 80, 80, {
  restitution: 0.8,
  friction: 0.5
})

const circle = Bodies.circle(300, 100, 40, {
  restitution: 0.9
})

// Add to world
World.add(engine.world, [ground, box, circle])

// Run
Render.run(render)
Runner.run(Runner.create(), engine)
</code></pre>
<p><strong>Collision events:</strong></p>
<pre><code class="language-js">Matter.Events.on(engine, 'collisionStart', (event) =&gt; {
  event.pairs.forEach(pair =&gt; {
    console.log('Collision between:', pair.bodyA.label, pair.bodyB.label)
  })
})
</code></pre>
<p><strong>Constraints:</strong></p>
<pre><code class="language-js">// Pin constraint
const pin = Matter.Constraint.create({
  pointA: { x: 400, y: 100 },
  bodyB: box,
  stiffness: 0.9
})

// Spring between bodies
const spring = Matter.Constraint.create({
  bodyA: box,
  bodyB: circle,
  stiffness: 0.01,
  length: 100
})

World.add(engine.world, [pin, spring])
</code></pre>
<p><strong>Mouse interaction:</strong></p>
<pre><code class="language-js">const mouse = Matter.Mouse.create(render.canvas)
const mouseConstraint = Matter.MouseConstraint.create(engine, {
  mouse: mouse,
  constraint: {
    stiffness: 0.2,
    render: { visible: false }
  }
})
World.add(engine.world, mouseConstraint)
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Beautiful default rendering</li>
<li>Great for learning/prototyping</li>
<li>Intuitive API</li>
<li>Good documentation</li>
<li>Active community</li>
<li>Deterministic by default — Matter.Runner now uses a fixed deterministic timestep (non-fixed timestep was removed in v0.20.0)</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>No CCD (fast objects can tunnel — use substepping to mitigate)</li>
<li>Performance issues with many bodies</li>
<li>No WASM option</li>
<li>Limited precision for complex simulations</li>
</ul>
<hr>
<h3>Planck.js — Box2D for JavaScript</h3>
<p>Planck.js is a complete rewrite of Box2D in JavaScript. Battle-tested physics, deterministic when using fixed timestep.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install planck
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import { World, Vec2, Box, Circle, Edge } from 'planck'

// Create world
const world = new World({
  gravity: Vec2(0, -10)
})

// Create ground
const ground = world.createBody()
ground.createFixture({
  shape: Edge(Vec2(-40, 0), Vec2(40, 0))
})

// Create dynamic box
const box = world.createBody({
  type: 'dynamic',
  position: Vec2(0, 10)
})
box.createFixture({
  shape: Box(1, 1),
  density: 1,
  friction: 0.3,
  restitution: 0.5
})
</code></pre>
<p><strong>Fixed timestep game loop:</strong></p>
<pre><code class="language-js">const TIMESTEP = 1 / 60
const VELOCITY_ITERATIONS = 8
const POSITION_ITERATIONS = 3

function gameLoop() {
  world.step(TIMESTEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS)
  
  // Iterate all bodies
  for (let body = world.getBodyList(); body; body = body.getNext()) {
    const pos = body.getPosition()
    const angle = body.getAngle()
    // Update your sprites...
  }
  
  requestAnimationFrame(gameLoop)
}
</code></pre>
<p><strong>Collision callbacks:</strong></p>
<pre><code class="language-js">world.on('begin-contact', (contact) =&gt; {
  const fixtureA = contact.getFixtureA()
  const fixtureB = contact.getFixtureB()
  console.log('Contact started')
})

world.on('end-contact', (contact) =&gt; {
  console.log('Contact ended')
})

world.on('pre-solve', (contact, oldManifold) =&gt; {
  // Can disable contact here
  // contact.setEnabled(false)
})
</code></pre>
<p><strong>Joints:</strong></p>
<pre><code class="language-js">import { RevoluteJoint, DistanceJoint, PrismaticJoint } from 'planck'

// Revolute joint (hinge)
const joint = world.createJoint(RevoluteJoint({
  bodyA: ground,
  bodyB: box,
  localAnchorA: Vec2(0, 5),
  localAnchorB: Vec2(-1, 0),
  enableMotor: true,
  maxMotorTorque: 1000,
  motorSpeed: 2
}))

// Distance joint (spring)
world.createJoint(DistanceJoint({
  bodyA: boxA,
  bodyB: boxB,
  localAnchorA: Vec2(0, 0),
  localAnchorB: Vec2(0, 0),
  length: 5,
  stiffness: 10,
  damping: 0.5
}))
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Deterministic with fixed timestep</li>
<li>Well-documented (Box2D docs apply)</li>
<li>Good performance</li>
<li>TypeScript support</li>
<li>Small bundle size</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>CCD does not handle joints, so fast objects connected by joints can stretch</li>
<li>Steeper learning curve than Matter.js</li>
<li>No built-in renderer</li>
<li>Box2D quirks (unit scale matters)</li>
</ul>
<hr>
<h3>p2-es — Flexible 2D physics</h3>
<p>p2-es is the maintained fork of p2.js. Great for games needing complex constraints and mechanisms.</p>
<p><strong>Install:</strong></p>
<pre><code class="language-bash">npm install p2-es
</code></pre>
<p><strong>Basic setup:</strong></p>
<pre><code class="language-js">import * as p2 from 'p2-es'

const world = new p2.World({
  gravity: [0, -9.81]
})

// Ground
const groundBody = new p2.Body({
  mass: 0, // static
  position: [0, -1]
})
groundBody.addShape(new p2.Plane())
world.addBody(groundBody)

// Dynamic circle
const circleBody = new p2.Body({
  mass: 1,
  position: [0, 5]
})
circleBody.addShape(new p2.Circle({ radius: 0.5 }))
world.addBody(circleBody)
</code></pre>
<p><strong>Advanced constraints:</strong></p>
<pre><code class="language-js">// Gear constraint
const gear = new p2.GearConstraint(bodyA, bodyB, {
  ratio: 2 // bodyB rotates twice as fast
})
world.addConstraint(gear)

// Prismatic constraint (slider)
const prismatic = new p2.PrismaticConstraint(bodyA, bodyB, {
  localAnchorA: [0, 0],
  localAnchorB: [0, 0],
  localAxisA: [1, 0],
  disableRotationalLock: false
})
world.addConstraint(prismatic)

// Lock constraint (weld)
const lock = new p2.LockConstraint(bodyA, bodyB)
world.addConstraint(lock)
</code></pre>
<p><strong>Contact materials:</strong></p>
<pre><code class="language-js">const ice = new p2.Material()
const rubber = new p2.Material()

const iceRubber = new p2.ContactMaterial(ice, rubber, {
  friction: 0.1,
  restitution: 0.9
})
world.addContactMaterial(iceRubber)

// Apply to shapes
iceBody.shapes[0].material = ice
rubberBody.shapes[0].material = rubber
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>Rich constraint system</li>
<li>Contact materials</li>
<li>Good for mechanisms/machines</li>
<li>Sleeping bodies (performance)</li>
<li>ES modules, tree-shakable</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>No built-in renderer</li>
<li>Some shape pairs unsupported</li>
<li>Less active than alternatives</li>
<li>Documentation gaps</li>
</ul>
<hr>
<h2>Performance tips</h2>
<h3>1. Use a fixed timestep</h3>
<pre><code class="language-js">const TIMESTEP = 1 / 60
let accumulator = 0

function gameLoop(deltaTime) {
  accumulator += deltaTime
  
  while (accumulator &gt;= TIMESTEP) {
    world.step(TIMESTEP)
    accumulator -= TIMESTEP
  }
  
  // Interpolate for smooth rendering
  const alpha = accumulator / TIMESTEP
  // lerp(previousState, currentState, alpha)
}
</code></pre>
<h3>2. Sleep inactive bodies</h3>
<p>Most engines support sleeping. Enable it:</p>
<pre><code class="language-js">// Cannon-es
world.allowSleep = true
body.allowSleep = true
body.sleepSpeedLimit = 0.1
body.sleepTimeLimit = 1

// Rapier
bodyDesc.setCanSleep(true)
</code></pre>
<h3>3. Use simple collision shapes</h3>
<pre><code class="language-js">// GOOD: Simple primitives
const sphere = new CANNON.Sphere(1)
const box = new CANNON.Box(new CANNON.Vec3(1, 1, 1))

// AVOID: Complex trimesh for dynamic bodies
const trimesh = new CANNON.Trimesh(vertices, indices) // Slow!
</code></pre>
<h3>4. Reduce solver iterations (carefully)</h3>
<pre><code class="language-js">// Cannon-es
world.solver.iterations = 5 // Default 10

// Rapier - configured at world creation
</code></pre>
<h3>5. Run physics in a Web Worker</h3>
<pre><code class="language-js">// main.js
const worker = new Worker('physics-worker.js')

worker.postMessage({ type: 'step', deltaTime: 1/60 })
worker.onmessage = (e) =&gt; {
  const { positions, rotations } = e.data
  // Update render objects
}

// physics-worker.js
importScripts('cannon-es.js')
const world = new CANNON.World()

onmessage = (e) =&gt; {
  if (e.data.type === 'step') {
    world.step(e.data.deltaTime)
    postMessage({
      positions: bodies.map(b =&gt; b.position.toArray()),
      rotations: bodies.map(b =&gt; b.quaternion.toArray())
    })
  }
}
</code></pre>
<hr>
<h2>When to use what</h2>
<table>
<thead>
<tr>
<th>Scenario</th>
<th>Recommended</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td>Production 3D game</td>
<td><strong>Rapier</strong></td>
<td>Best performance, modern API, vehicles</td>
</tr>
<tr>
<td>3D game prototype</td>
<td><strong>Cannon-es</strong></td>
<td>Simple, debuggable</td>
</tr>
<tr>
<td>Soft bodies, cloth, ropes</td>
<td><strong>Ammo.js</strong> or <strong>Jolt</strong></td>
<td>Both support cloth/soft bodies; Jolt's WASM port (JoltPhysics.js) is more actively maintained</td>
</tr>
<tr>
<td>Simple 3D browser game</td>
<td><strong>Oimo.js</strong></td>
<td>Tiny, sufficient</td>
</tr>
<tr>
<td>2D game jam</td>
<td><strong>Matter.js</strong></td>
<td>Fast setup, built-in rendering</td>
</tr>
<tr>
<td>Precise platformer</td>
<td><strong>Planck.js</strong></td>
<td>Fixed timestep determinism, well-documented</td>
</tr>
<tr>
<td>Complex 2D mechanisms</td>
<td><strong>p2-es</strong></td>
<td>Rich constraint system</td>
</tr>
<tr>
<td>Performance-critical 2D</td>
<td><strong>Box2D WASM</strong></td>
<td>Fastest 2D option, true CCD</td>
</tr>
</tbody>
</table>
<hr>
<h2>Integration with renderers</h2>
<h3>Three.js + Rapier</h3>
<pre><code class="language-js">import * as THREE from 'three'
import RAPIER from '@dimforge/rapier3d'

await RAPIER.init()

const scene = new THREE.Scene()
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 })

const bodies = new Map() // physics body -&gt; mesh

function createPhysicsBox(x, y, z) {
  // Physics
  const bodyDesc = RAPIER.RigidBodyDesc.dynamic().setTranslation(x, y, z)
  const body = world.createRigidBody(bodyDesc)
  const collider = RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5)
  world.createCollider(collider, body)
  
  // Render
  const mesh = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshStandardMaterial({ color: 0x00ff00 })
  )
  scene.add(mesh)
  
  bodies.set(body, mesh)
  return body
}

function syncPhysics() {
  bodies.forEach((mesh, body) =&gt; {
    const pos = body.translation()
    const rot = body.rotation()
    mesh.position.set(pos.x, pos.y, pos.z)
    mesh.quaternion.set(rot.x, rot.y, rot.z, rot.w)
  })
}
</code></pre>
<h3>PixiJS + Matter.js</h3>
<pre><code class="language-js">import * as PIXI from 'pixi.js'
import Matter from 'matter-js'

const app = new PIXI.Application({ width: 800, height: 600 })
document.body.appendChild(app.view)

const engine = Matter.Engine.create()
const bodies = new Map()

function createPhysicsSprite(texture, x, y, width, height) {
  // Physics
  const body = Matter.Bodies.rectangle(x, y, width, height)
  Matter.World.add(engine.world, body)
  
  // Render
  const sprite = new PIXI.Sprite(texture)
  sprite.anchor.set(0.5)
  app.stage.addChild(sprite)
  
  bodies.set(body, sprite)
  return body
}

app.ticker.add(() =&gt; {
  Matter.Engine.update(engine, 1000 / 60)
  
  bodies.forEach((sprite, body) =&gt; {
    sprite.position.set(body.position.x, body.position.y)
    sprite.rotation = body.angle
  })
})
</code></pre>
<hr>
<h2>Common gotchas</h2>
<h3>Scale matters</h3>
<p>Physics engines work best with real-world scale (1 unit = 1 meter). Don't use pixel coordinates directly.</p>
<pre><code class="language-js">// BAD: Using pixel positions
const body = Bodies.circle(400, 300, 50) // 50 pixel radius?

// GOOD: Use a scale factor
const SCALE = 50 // 50 pixels per meter
const body = Bodies.circle(8, 6, 1) // 1 meter radius
// Then multiply by SCALE when rendering
</code></pre>
<h3>Memory leaks with WASM engines</h3>
<p>Always clean up bodies when removing them:</p>
<pre><code class="language-js">// Rapier
world.removeRigidBody(body)

// Ammo.js
physicsWorld.removeRigidBody(body)
Ammo.destroy(body)
Ammo.destroy(shape)
Ammo.destroy(motionState)
</code></pre>
<h3>Tunneling (objects passing through each other)</h3>
<p>Fast-moving objects can tunnel through thin walls. Solutions:</p>
<pre><code class="language-js">// Rapier: Enable CCD
const bodyDesc = RAPIER.RigidBodyDesc.dynamic().setCcdEnabled(true)

// Cannon-es: Use smaller timesteps or thicker walls
world.step(1/120) // 120 Hz instead of 60
</code></pre>
<hr>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/webgl-fundamentals-for-games">WebGL fundamentals for game developers</a></li>
<li><a href="/tutorials/web-workers-game-logic">Web Workers for game logic</a> — offload physics to a Worker thread</li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a> — the fixed timestep pattern used by every physics engine</li>
<li><a href="/guides/web-games-stack-2026">Web Games Tech Stack in 2026</a> — how physics engines fit into the wider stack</li>
<li><a href="/guides/web-game-engines-comparison">Web Game Engines Comparison</a> — engines with built-in physics support</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://rapier.rs/docs/">Rapier documentation</a> — official Rapier physics docs and examples</li>
<li><a href="https://pmndrs.github.io/cannon-es/docs/">Cannon-es documentation</a> — API reference and guides</li>
<li><a href="https://brm.io/matter-js/docs/">Matter.js documentation</a> — full API reference</li>
<li><a href="https://piqnt.com/planck.js/">Planck.js documentation</a> — Box2D for JavaScript</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gamepad API for web games]]></title>
            <link>https://app.cinevva.com/tutorials/gamepad-api</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/gamepad-api</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Full gamepad support: detection, button mapping, analog sticks, vibration, and handling multiple controllers. Console-quality input on the web.]]></description>
            <content:encoded><![CDATA[<h1>Gamepad API for web games</h1>
<p>The Gamepad API brings console-quality controller support to web games. Support Xbox, PlayStation, Switch Pro, and generic controllers.</p>
<h2>1) Detecting gamepads</h2>
<pre><code class="language-js">window.addEventListener('gamepadconnected', (e) =&gt; {
  console.log('Gamepad connected:', e.gamepad.id)
  console.log('Index:', e.gamepad.index)
  console.log('Buttons:', e.gamepad.buttons.length)
  console.log('Axes:', e.gamepad.axes.length)
})

window.addEventListener('gamepaddisconnected', (e) =&gt; {
  console.log('Gamepad disconnected:', e.gamepad.id)
})
</code></pre>
<h2>2) Polling gamepad state</h2>
<p>Gamepad state must be polled (not event-driven):</p>
<pre><code class="language-js">function pollGamepads() {
  const gamepads = navigator.getGamepads()
  
  for (const gamepad of gamepads) {
    if (gamepad) {
      processGamepad(gamepad)
    }
  }
}

// Call in your game loop
function gameLoop() {
  pollGamepads()
  update()
  render()
  requestAnimationFrame(gameLoop)
}
</code></pre>
<h2>3) Standard button mapping</h2>
<p>The &quot;standard&quot; mapping (most Xbox/PlayStation controllers):</p>
<pre><code class="language-js">const BUTTONS = {
  A: 0,           // Cross (PS) / A (Xbox)
  B: 1,           // Circle (PS) / B (Xbox)
  X: 2,           // Square (PS) / X (Xbox)
  Y: 3,           // Triangle (PS) / Y (Xbox)
  LB: 4,          // L1 (PS) / LB (Xbox)
  RB: 5,          // R1 (PS) / RB (Xbox)
  LT: 6,          // L2 (PS) / LT (Xbox)
  RT: 7,          // R2 (PS) / RT (Xbox)
  SELECT: 8,      // Share (PS) / Back (Xbox)
  START: 9,       // Options (PS) / Start (Xbox)
  L3: 10,         // Left stick press
  R3: 11,         // Right stick press
  DPAD_UP: 12,
  DPAD_DOWN: 13,
  DPAD_LEFT: 14,
  DPAD_RIGHT: 15,
  HOME: 16,       // PS button / Xbox button
}

const AXES = {
  LEFT_X: 0,
  LEFT_Y: 1,
  RIGHT_X: 2,
  RIGHT_Y: 3,
}
</code></pre>
<h2>4) Reading buttons and sticks</h2>
<pre><code class="language-js">function processGamepad(gamepad) {
  // Buttons (digital or analog)
  const jump = gamepad.buttons[BUTTONS.A].pressed
  const shoot = gamepad.buttons[BUTTONS.X].pressed
  
  // Triggers (analog 0-1)
  const leftTrigger = gamepad.buttons[BUTTONS.LT].value
  const rightTrigger = gamepad.buttons[BUTTONS.RT].value
  
  // Sticks (analog -1 to 1)
  const leftX = gamepad.axes[AXES.LEFT_X]
  const leftY = gamepad.axes[AXES.LEFT_Y]
  const rightX = gamepad.axes[AXES.RIGHT_X]
  const rightY = gamepad.axes[AXES.RIGHT_Y]
  
  return { jump, shoot, leftTrigger, rightTrigger, leftX, leftY, rightX, rightY }
}
</code></pre>
<h2>5) Deadzone handling</h2>
<p>Sticks rarely rest at exactly 0:</p>
<pre><code class="language-js">function applyDeadzone(value, deadzone = 0.15) {
  if (Math.abs(value) &lt; deadzone) return 0
  
  // Rescale remaining range to 0-1
  const sign = Math.sign(value)
  const adjusted = (Math.abs(value) - deadzone) / (1 - deadzone)
  return sign * adjusted
}

function getStickInput(gamepad) {
  return {
    leftX: applyDeadzone(gamepad.axes[AXES.LEFT_X]),
    leftY: applyDeadzone(gamepad.axes[AXES.LEFT_Y]),
    rightX: applyDeadzone(gamepad.axes[AXES.RIGHT_X]),
    rightY: applyDeadzone(gamepad.axes[AXES.RIGHT_Y]),
  }
}
</code></pre>
<h2>6) Radial deadzone (better for 2D movement)</h2>
<pre><code class="language-js">function applyRadialDeadzone(x, y, deadzone = 0.15) {
  const magnitude = Math.sqrt(x * x + y * y)
  
  if (magnitude &lt; deadzone) {
    return { x: 0, y: 0 }
  }
  
  const normalized = {
    x: x / magnitude,
    y: y / magnitude,
  }
  
  const adjusted = (magnitude - deadzone) / (1 - deadzone)
  
  return {
    x: normalized.x * adjusted,
    y: normalized.y * adjusted,
  }
}

// Usage
const stick = applyRadialDeadzone(
  gamepad.axes[AXES.LEFT_X],
  gamepad.axes[AXES.LEFT_Y]
)
player.vx = stick.x * player.speed
player.vy = stick.y * player.speed
</code></pre>
<h2>7) Complete gamepad manager</h2>
<pre><code class="language-js">class GamepadManager {
  constructor() {
    this.gamepads = new Map()
    this.prevState = new Map()
    
    window.addEventListener('gamepadconnected', (e) =&gt; {
      this.gamepads.set(e.gamepad.index, e.gamepad)
      console.log('Connected:', e.gamepad.id)
    })
    
    window.addEventListener('gamepaddisconnected', (e) =&gt; {
      this.gamepads.delete(e.gamepad.index)
      this.prevState.delete(e.gamepad.index)
    })
  }
  
  poll() {
    const gamepads = navigator.getGamepads()
    for (const gp of gamepads) {
      if (gp) this.gamepads.set(gp.index, gp)
    }
  }
  
  getState(index = 0) {
    const gp = this.gamepads.get(index)
    if (!gp) return null
    
    const stick = applyRadialDeadzone(gp.axes[0], gp.axes[1])
    const rightStick = applyRadialDeadzone(gp.axes[2], gp.axes[3])
    
    return {
      connected: true,
      leftStick: stick,
      rightStick: rightStick,
      
      // Face buttons
      a: gp.buttons[0].pressed,
      b: gp.buttons[1].pressed,
      x: gp.buttons[2].pressed,
      y: gp.buttons[3].pressed,
      
      // Bumpers
      lb: gp.buttons[4].pressed,
      rb: gp.buttons[5].pressed,
      
      // Triggers (analog)
      lt: gp.buttons[6].value,
      rt: gp.buttons[7].value,
      
      // D-pad
      dpadUp: gp.buttons[12].pressed,
      dpadDown: gp.buttons[13].pressed,
      dpadLeft: gp.buttons[14].pressed,
      dpadRight: gp.buttons[15].pressed,
      
      // Meta
      select: gp.buttons[8].pressed,
      start: gp.buttons[9].pressed,
    }
  }
  
  isPressed(index, button) {
    const gp = this.gamepads.get(index)
    return gp?.buttons[button]?.pressed || false
  }
  
  wasJustPressed(index, button) {
    const current = this.isPressed(index, button)
    const prev = this.prevState.get(index)?.[button] || false
    return current &amp;&amp; !prev
  }
  
  endFrame() {
    for (const [index, gp] of this.gamepads) {
      const state = {}
      for (let i = 0; i &lt; gp.buttons.length; i++) {
        state[i] = gp.buttons[i].pressed
      }
      this.prevState.set(index, state)
    }
  }
}

// Usage
const gamepadManager = new GamepadManager()

function update() {
  gamepadManager.poll()
  
  const state = gamepadManager.getState(0)
  if (state) {
    player.vx = state.leftStick.x * player.speed
    player.vy = state.leftStick.y * player.speed
    
    if (gamepadManager.wasJustPressed(0, BUTTONS.A)) {
      player.jump()
    }
  }
  
  gamepadManager.endFrame()
}
</code></pre>
<h2>8) Vibration / haptic feedback</h2>
<pre><code class="language-js">function vibrate(gamepad, duration = 200, weakMagnitude = 0.5, strongMagnitude = 0.5) {
  if (gamepad.vibrationActuator) {
    gamepad.vibrationActuator.playEffect('dual-rumble', {
      startDelay: 0,
      duration,
      weakMagnitude,   // High frequency motor
      strongMagnitude, // Low frequency motor
    })
  }
}

// Usage
function onPlayerHit() {
  const gp = navigator.getGamepads()[0]
  if (gp) vibrate(gp, 150, 0.3, 0.6)
}

function onExplosion() {
  const gp = navigator.getGamepads()[0]
  if (gp) vibrate(gp, 300, 0.8, 1.0)
}
</code></pre>
<h2>9) Multiple players</h2>
<pre><code class="language-js">class LocalMultiplayer {
  constructor(maxPlayers = 4) {
    this.maxPlayers = maxPlayers
    this.players = []
  }
  
  getActivePlayers() {
    const gamepads = navigator.getGamepads()
    const active = []
    
    for (let i = 0; i &lt; this.maxPlayers; i++) {
      if (gamepads[i]) {
        active.push({
          index: i,
          gamepad: gamepads[i],
          state: this.getState(gamepads[i])
        })
      }
    }
    
    return active
  }
  
  getState(gp) {
    // ... same as before
  }
}

// In game loop
const multiplayer = new LocalMultiplayer(4)

function update() {
  const players = multiplayer.getActivePlayers()
  
  for (const { index, state } of players) {
    updatePlayer(index, state)
  }
}
</code></pre>
<h2>10) Fallback and combined input</h2>
<p>Support both keyboard and gamepad:</p>
<pre><code class="language-js">class InputManager {
  constructor() {
    this.keyboard = new KeyboardInput()
    this.gamepad = new GamepadManager()
  }
  
  poll() {
    this.gamepad.poll()
  }
  
  getInput(playerIndex = 0) {
    const gpState = this.gamepad.getState(playerIndex)
    const kbState = this.keyboard.getState()
    
    // Combine inputs (gamepad takes priority for analog)
    return {
      moveX: gpState?.leftStick.x || (kbState.left ? -1 : kbState.right ? 1 : 0),
      moveY: gpState?.leftStick.y || (kbState.up ? -1 : kbState.down ? 1 : 0),
      jump: gpState?.a || kbState.space,
      shoot: gpState?.x || kbState.z,
      pause: gpState?.start || kbState.escape,
    }
  }
  
  endFrame() {
    this.gamepad.endFrame()
    this.keyboard.endFrame()
  }
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/game-input-handling">Game input handling</a></li>
<li><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a></li>
<li><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a></li>
<li><a href="/tutorials/pointer-lock-fps">Pointer Lock for FPS games</a> — combining gamepad with mouse look</li>
<li><a href="/guides/co-op-game-design">Co-op Game Design</a> — designing for multiple controller inputs in local co-op</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API">MDN: Gamepad API</a> — full API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API">MDN: Using the Gamepad API</a> — step-by-step guide</li>
<li><a href="https://gamepad-tester.com/">Gamepad Tester</a> — test your controller mappings in the browser</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iframe embedding best practices for games]]></title>
            <link>https://app.cinevva.com/tutorials/iframe-embedding-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/iframe-embedding-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Embed web games in iframes correctly: security, communication, fullscreen, and platform requirements. Make your game embeddable everywhere.]]></description>
            <content:encoded><![CDATA[<h1>Iframe embedding best practices for games</h1>
<p>Many platforms (<a href="http://Itch.io">Itch.io</a>, Newgrounds, Cinevva, your own site) embed games in iframes. This tutorial covers how to make your game work well when embedded.</p>
<h2>1) Basic embeddable setup</h2>
<p>Your game should work without requiring full page control:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;UTF-8&quot;&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
  &lt;style&gt;
    * { margin: 0; padding: 0; }
    html, body { width: 100%; height: 100%; overflow: hidden; }
    canvas { display: block; width: 100%; height: 100%; }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;canvas id=&quot;game&quot;&gt;&lt;/canvas&gt;
  &lt;script src=&quot;game.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>2) Detecting iframe context</h2>
<pre><code class="language-js">const isEmbedded = window.self !== window.top

if (isEmbedded) {
  // Adjust behavior for embedded context
  hideExternalLinks()
  adjustUIForSmallSize()
}

function hideExternalLinks() {
  document.querySelectorAll('a[target=&quot;_blank&quot;]').forEach(link =&gt; {
    link.style.display = 'none'
  })
}
</code></pre>
<h2>3) Allow necessary iframe permissions</h2>
<p>The parent page controls what your iframe can do. Common permissions:</p>
<pre><code class="language-html">&lt;iframe 
  src=&quot;https://game.example.com&quot;
  allow=&quot;fullscreen; autoplay; gamepad; pointer-lock&quot;
  sandbox=&quot;allow-scripts allow-same-origin allow-pointer-lock allow-popups&quot;
&gt;&lt;/iframe&gt;
</code></pre>
<p>Your game should handle missing permissions gracefully:</p>
<pre><code class="language-js">// Check if fullscreen is available
const canFullscreen = document.fullscreenEnabled || document.webkitFullscreenEnabled

if (!canFullscreen) {
  document.getElementById('fullscreen-btn').style.display = 'none'
}
</code></pre>
<h2>4) Fullscreen from iframe</h2>
<p>Fullscreen requires the <code>allow=&quot;fullscreen&quot;</code> attribute:</p>
<pre><code class="language-js">async function requestFullscreen() {
  const elem = document.documentElement
  
  try {
    if (elem.requestFullscreen) {
      await elem.requestFullscreen()
    } else if (elem.webkitRequestFullscreen) {
      await elem.webkitRequestFullscreen()
    }
  } catch (err) {
    // Fullscreen not allowed - show message
    showMessage('Fullscreen not available when embedded')
  }
}
</code></pre>
<h2>5) Communicating with parent page</h2>
<p>Use <code>postMessage</code> for safe cross-origin communication:</p>
<p><strong>In your game:</strong></p>
<pre><code class="language-js">// Send message to parent
function notifyParent(type, data) {
  if (window.parent !== window) {
    window.parent.postMessage({ type, data, source: 'game' }, '*')
  }
}

// Receive messages from parent
window.addEventListener('message', (event) =&gt; {
  // Validate origin if needed
  // if (event.origin !== 'https://trusted-host.com') return
  
  const { type, data } = event.data
  
  switch (type) {
    case 'pause':
      pauseGame()
      break
    case 'resume':
      resumeGame()
      break
    case 'setVolume':
      setVolume(data.volume)
      break
  }
})

// Notify when game is ready
window.addEventListener('load', () =&gt; {
  notifyParent('ready', { width: 800, height: 600 })
})

// Notify on game events
function onGameOver(score) {
  notifyParent('gameover', { score })
}
</code></pre>
<p><strong>In parent page:</strong></p>
<pre><code class="language-js">const iframe = document.getElementById('game-iframe')

iframe.addEventListener('load', () =&gt; {
  // Listen for messages from game
  window.addEventListener('message', (event) =&gt; {
    if (event.source !== iframe.contentWindow) return
    if (event.data.source !== 'game') return
    
    const { type, data } = event.data
    
    if (type === 'ready') {
      console.log('Game ready:', data)
    }
    if (type === 'gameover') {
      showScoreModal(data.score)
    }
  })
})

// Send commands to game
function pauseGame() {
  iframe.contentWindow.postMessage({ type: 'pause' }, '*')
}
</code></pre>
<h2>6) Handling focus</h2>
<p>Iframes can lose focus, breaking keyboard input:</p>
<pre><code class="language-js">// Auto-focus canvas when clicked
canvas.addEventListener('click', () =&gt; {
  canvas.focus()
})

// Make canvas focusable
canvas.tabIndex = 1

// Handle focus loss
window.addEventListener('blur', () =&gt; {
  // Reset held keys
  input.left = input.right = input.up = input.down = false
  
  if (isEmbedded) {
    // Optionally pause
    // pauseGame()
  }
})

// Request focus from parent
function requestFocus() {
  notifyParent('requestFocus', {})
}
</code></pre>
<h2>7) Responsive embedded size</h2>
<p>Handle various embed dimensions:</p>
<pre><code class="language-js">function handleResize() {
  const width = window.innerWidth
  const height = window.innerHeight
  
  // Adjust UI based on size
  if (width &lt; 400 || height &lt; 300) {
    enableCompactUI()
  } else {
    enableFullUI()
  }
  
  // Scale game appropriately
  resizeCanvas(width, height)
}

window.addEventListener('resize', handleResize)
handleResize()
</code></pre>
<h2>8) Loading indicator for embeds</h2>
<p>Show something immediately:</p>
<pre><code class="language-js">// Inline in HTML for instant display
const loadingHTML = `
  &lt;div id=&quot;loading&quot; style=&quot;
    position: fixed;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #1a1a2e;
    color: #fff;
    font-family: sans-serif;
  &quot;&gt;
    &lt;div&gt;
      &lt;div class=&quot;spinner&quot;&gt;&lt;/div&gt;
      &lt;p&gt;Loading...&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
`

// Remove when game is ready
function hideLoading() {
  const loading = document.getElementById('loading')
  if (loading) {
    loading.style.opacity = '0'
    loading.style.transition = 'opacity 0.3s'
    setTimeout(() =&gt; loading.remove(), 300)
  }
}
</code></pre>
<h2>9) Platform-specific SDKs</h2>
<p>Some platforms have their own APIs:</p>
<p><strong><a href="http://Itch.io">Itch.io</a>:</strong></p>
<pre><code class="language-js">// No SDK required, but can use postMessage for achievements
window.parent.postMessage({ type: 'itch-achievement', data: { id: 'first-win' }}, '*')
</code></pre>
<p><strong>Newgrounds:</strong></p>
<pre><code class="language-js">// Include Newgrounds.io SDK
const ngio = new Newgrounds.io.core('APP_ID', 'AES_KEY')
ngio.callComponent('Medal.unlock', { id: 12345 })
</code></pre>
<p><strong>Cinevva:</strong></p>
<pre><code class="language-js">// Signal game is ready
window.parent.postMessage({ type: 'cinevva:ready' }, '*')

// Signal playable state
window.parent.postMessage({ type: 'cinevva:playable' }, '*')
</code></pre>
<h2>10) Security considerations</h2>
<pre><code class="language-js">// Validate message origins when sensitive
window.addEventListener('message', (event) =&gt; {
  const trustedOrigins = [
    'https://itch.io',
    'https://cinevva.com',
    'https://yoursite.com'
  ]
  
  if (!trustedOrigins.includes(event.origin)) {
    return // Ignore untrusted messages
  }
  
  // Process message...
})

// Don't expose sensitive operations via postMessage
// Only allow whitelisted commands
const allowedCommands = ['pause', 'resume', 'setVolume', 'mute']

window.addEventListener('message', (event) =&gt; {
  const { type } = event.data
  if (!allowedCommands.includes(type)) return
  
  // Handle command...
})
</code></pre>
<h2>Testing checklist</h2>
<ul>
<li><strong>Local testing</strong>: Use a simple HTTP server, not <code>file://</code></li>
<li><strong>Cross-origin</strong>: Test with actual iframe embedding</li>
<li><strong>Permissions</strong>: Test with restricted sandbox</li>
<li><strong>Focus</strong>: Test keyboard after clicking outside iframe</li>
<li><strong>Resize</strong>: Test at various embed sizes</li>
<li><strong>Mobile</strong>: Test touch in embedded context</li>
</ul>
<pre><code class="language-html">&lt;!-- Test embed page --&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body style=&quot;background: #333; padding: 20px;&quot;&gt;
  &lt;h1 style=&quot;color: #fff;&quot;&gt;Embed Test&lt;/h1&gt;
  &lt;iframe 
    src=&quot;http://localhost:8000&quot; 
    width=&quot;800&quot; 
    height=&quot;600&quot;
    allow=&quot;fullscreen; autoplay; gamepad&quot;
  &gt;&lt;/iframe&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a></li>
<li><a href="/creators">For creators</a></li>
<li><a href="/tutorials/coop-coep-sharedarraybuffer">COOP/COEP and SharedArrayBuffer</a> — cross-origin headers that affect iframe embedding</li>
<li><a href="/guides/itch-io-launch-guide">How to Launch Your Game on itch.io</a> — <a href="http://itch.io">itch.io</a> embeds browser games in iframes natively</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe">MDN: iframe element</a> — full reference for iframe attributes</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy">MDN: Permissions Policy</a> — controlling which features iframes can use</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">MDN: postMessage API</a> — communicating between iframe and parent</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Save and load game state with IndexedDB]]></title>
            <link>https://app.cinevva.com/tutorials/indexeddb-game-saves</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/indexeddb-game-saves</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Persistent game saves with IndexedDB: storing progress, settings, and large data. Async patterns that won't block your game.]]></description>
            <content:encoded><![CDATA[<h1>Save and load game state with IndexedDB</h1>
<p>IndexedDB is the best option for persistent game data in the browser. It handles large amounts of data, works offline, and doesn't block the main thread.</p>
<h2>1) Why IndexedDB over localStorage?</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>localStorage</th>
<th>IndexedDB</th>
</tr>
</thead>
<tbody>
<tr>
<td>Storage limit</td>
<td>~5-10 MB</td>
<td>50+ MB (often GB)</td>
</tr>
<tr>
<td>Data types</td>
<td>Strings only</td>
<td>Objects, blobs, arrays</td>
</tr>
<tr>
<td>Async</td>
<td>No (blocks)</td>
<td>Yes</td>
</tr>
<tr>
<td>Indexed queries</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody>
</table>
<p>For games, IndexedDB is almost always the right choice.</p>
<h2>2) Opening a database</h2>
<pre><code class="language-js">function openGameDB() {
  return new Promise((resolve, reject) =&gt; {
    const request = indexedDB.open('MyGame', 1)
    
    request.onerror = () =&gt; reject(request.error)
    request.onsuccess = () =&gt; resolve(request.result)
    
    request.onupgradeneeded = (event) =&gt; {
      const db = event.target.result
      
      // Create stores
      if (!db.objectStoreNames.contains('saves')) {
        db.createObjectStore('saves', { keyPath: 'slot' })
      }
      if (!db.objectStoreNames.contains('settings')) {
        db.createObjectStore('settings', { keyPath: 'key' })
      }
    }
  })
}
</code></pre>
<h2>3) Saving game state</h2>
<pre><code class="language-js">async function saveGame(slot, gameState) {
  const db = await openGameDB()
  
  return new Promise((resolve, reject) =&gt; {
    const tx = db.transaction('saves', 'readwrite')
    const store = tx.objectStore('saves')
    
    const saveData = {
      slot,
      state: gameState,
      timestamp: Date.now(),
    }
    
    const request = store.put(saveData)
    request.onsuccess = () =&gt; resolve()
    request.onerror = () =&gt; reject(request.error)
  })
}
</code></pre>
<h2>4) Loading game state</h2>
<pre><code class="language-js">async function loadGame(slot) {
  const db = await openGameDB()
  
  return new Promise((resolve, reject) =&gt; {
    const tx = db.transaction('saves', 'readonly')
    const store = tx.objectStore('saves')
    
    const request = store.get(slot)
    request.onsuccess = () =&gt; resolve(request.result?.state || null)
    request.onerror = () =&gt; reject(request.error)
  })
}
</code></pre>
<h2>5) Listing all saves</h2>
<pre><code class="language-js">async function listSaves() {
  const db = await openGameDB()
  
  return new Promise((resolve, reject) =&gt; {
    const tx = db.transaction('saves', 'readonly')
    const store = tx.objectStore('saves')
    
    const request = store.getAll()
    request.onsuccess = () =&gt; resolve(request.result)
    request.onerror = () =&gt; reject(request.error)
  })
}
</code></pre>
<h2>6) Deleting a save</h2>
<pre><code class="language-js">async function deleteSave(slot) {
  const db = await openGameDB()
  
  return new Promise((resolve, reject) =&gt; {
    const tx = db.transaction('saves', 'readwrite')
    const store = tx.objectStore('saves')
    
    const request = store.delete(slot)
    request.onsuccess = () =&gt; resolve()
    request.onerror = () =&gt; reject(request.error)
  })
}
</code></pre>
<h2>7) A complete GameStorage class</h2>
<pre><code class="language-js">class GameStorage {
  constructor(dbName = 'GameData', version = 1) {
    this.dbName = dbName
    this.version = version
    this.db = null
  }
  
  async init() {
    this.db = await this.openDB()
  }
  
  openDB() {
    return new Promise((resolve, reject) =&gt; {
      const request = indexedDB.open(this.dbName, this.version)
      request.onerror = () =&gt; reject(request.error)
      request.onsuccess = () =&gt; resolve(request.result)
      request.onupgradeneeded = (e) =&gt; {
        const db = e.target.result
        if (!db.objectStoreNames.contains('saves')) {
          db.createObjectStore('saves', { keyPath: 'slot' })
        }
        if (!db.objectStoreNames.contains('settings')) {
          db.createObjectStore('settings', { keyPath: 'key' })
        }
        if (!db.objectStoreNames.contains('assets')) {
          db.createObjectStore('assets', { keyPath: 'url' })
        }
      }
    })
  }
  
  async save(slot, data) {
    const tx = this.db.transaction('saves', 'readwrite')
    tx.objectStore('saves').put({ slot, data, timestamp: Date.now() })
    return tx.complete
  }
  
  async load(slot) {
    const tx = this.db.transaction('saves', 'readonly')
    const result = await this.promisify(tx.objectStore('saves').get(slot))
    return result?.data || null
  }
  
  async setSetting(key, value) {
    const tx = this.db.transaction('settings', 'readwrite')
    tx.objectStore('settings').put({ key, value })
  }
  
  async getSetting(key, defaultValue = null) {
    const tx = this.db.transaction('settings', 'readonly')
    const result = await this.promisify(tx.objectStore('settings').get(key))
    return result?.value ?? defaultValue
  }
  
  promisify(request) {
    return new Promise((resolve, reject) =&gt; {
      request.onsuccess = () =&gt; resolve(request.result)
      request.onerror = () =&gt; reject(request.error)
    })
  }
}
</code></pre>
<h2>8) Storing binary data (textures, audio)</h2>
<p>IndexedDB handles Blobs and ArrayBuffers:</p>
<pre><code class="language-js">async function cacheAsset(url, blob) {
  const tx = db.transaction('assets', 'readwrite')
  tx.objectStore('assets').put({ url, blob, cached: Date.now() })
}

async function getCachedAsset(url) {
  const tx = db.transaction('assets', 'readonly')
  const result = await promisify(tx.objectStore('assets').get(url))
  return result?.blob || null
}
</code></pre>
<h2>9) Autosave pattern</h2>
<pre><code class="language-js">class AutoSave {
  constructor(storage, interval = 60000) {
    this.storage = storage
    this.interval = interval
    this.timer = null
    this.dirty = false
  }
  
  markDirty() {
    this.dirty = true
  }
  
  start(getState) {
    this.timer = setInterval(async () =&gt; {
      if (this.dirty) {
        await this.storage.save('autosave', getState())
        this.dirty = false
        console.log('Autosaved')
      }
    }, this.interval)
  }
  
  stop() {
    clearInterval(this.timer)
  }
}
</code></pre>
<h2>10) Error handling and fallbacks</h2>
<pre><code class="language-js">async function safeLoad(slot, defaultState) {
  try {
    const saved = await loadGame(slot)
    if (saved) {
      // Validate/migrate old saves if needed
      return migrateSave(saved)
    }
  } catch (err) {
    console.warn('Failed to load save:', err)
  }
  return defaultState
}

function migrateSave(save) {
  // Handle old save formats
  if (!save.version) {
    save.version = 1
    save.settings = save.settings || {}
  }
  return save
}
</code></pre>
<h2>11) Make saves survive eviction</h2>
<p>IndexedDB isn't guaranteed to stick around. By default an origin uses &quot;best-effort&quot; storage, and the browser can evict it when the disk fills up or, on Safari/WebKit, after a stretch of no user interaction with your site. For game saves that's exactly the data you don't want to lose.</p>
<p>Request persistent storage so the browser won't clear your data without an explicit user action:</p>
<pre><code class="language-js">async function makeStoragePersistent() {
  if (navigator.storage &amp;&amp; navigator.storage.persist) {
    const persisted = await navigator.storage.persist()
    console.log(persisted ? 'Saves are protected from eviction' : 'Saves may be evicted under storage pressure')
    return persisted
  }
  return false
}
</code></pre>
<p>Browsers decide whether to grant it based on engagement signals (how much the user interacts with your site, whether it's installed as a PWA), so don't assume it always succeeds. You can also check how much room you have before writing large saves or cached assets:</p>
<pre><code class="language-js">async function checkStorage() {
  if (navigator.storage &amp;&amp; navigator.storage.estimate) {
    const { usage, quota } = await navigator.storage.estimate()
    console.log(`Using ${usage} of ${quota} bytes`)
  }
}
</code></pre>
<p>Both APIs need a secure context (HTTPS or localhost).</p>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/pwa-offline-games">PWA for offline games</a></li>
<li><a href="/tutorials/service-workers-caching">Service workers for game caching</a></li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/streaming-asset-loading">Streaming asset loading</a> — using IndexedDB as an asset cache</li>
<li><a href="/tutorials/analytics-web-games">Analytics for web games</a> — tracking save/load patterns to understand player behavior</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">MDN: IndexedDB API</a> — full API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">MDN: Using IndexedDB</a> — step-by-step guide</li>
<li><a href="https://github.com/jakearchibald/idb">idb library</a> — a tiny Promise-based IndexedDB wrapper</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile-friendly web games]]></title>
            <link>https://app.cinevva.com/tutorials/mobile-friendly-web-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/mobile-friendly-web-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Make web games work on mobile: touch controls, performance, viewport, battery, and responsive design. Reach the largest gaming platform.]]></description>
            <content:encoded><![CDATA[<h1>Mobile-friendly web games</h1>
<p>Mobile is the biggest gaming platform. A few adjustments make your web game work great on phones and tablets.</p>
<h2>1) Viewport setup</h2>
<p>Prevent zoom and ensure proper scaling:</p>
<pre><code class="language-html">&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no&quot;&gt;
</code></pre>
<h2>2) Fullscreen canvas</h2>
<pre><code class="language-css">* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #000;
  touch-action: none; /* Prevent browser gestures */
}

#game {
  display: block;
  width: 100%;
  height: 100%;
}
</code></pre>
<p>If you size UI off viewport height instead of <code>height: 100%</code>, prefer the dynamic viewport units <code>dvh</code>, <code>svh</code>, and <code>lvh</code> over <code>vh</code>. They account for the mobile browser's collapsing/expanding toolbar, which <code>100vh</code> ignores (on iOS <code>100vh</code> is the toolbar-hidden height, so the bottom of your layout gets clipped). These units reached Baseline Widely Available and are supported in Chrome/Edge 108+, Firefox 101+, and Safari/iOS Safari 15.4+, roughly 92% of users.</p>
<h2>3) Touch event handling</h2>
<pre><code class="language-js">const canvas = document.getElementById('game')

// Prevent default touch behaviors
canvas.addEventListener('touchstart', (e) =&gt; e.preventDefault(), { passive: false })
canvas.addEventListener('touchmove', (e) =&gt; e.preventDefault(), { passive: false })

// Track touches
const touches = new Map()

canvas.addEventListener('touchstart', (e) =&gt; {
  for (const touch of e.changedTouches) {
    touches.set(touch.identifier, {
      x: touch.clientX,
      y: touch.clientY,
      startX: touch.clientX,
      startY: touch.clientY,
    })
  }
})

canvas.addEventListener('touchmove', (e) =&gt; {
  for (const touch of e.changedTouches) {
    const t = touches.get(touch.identifier)
    if (t) {
      t.x = touch.clientX
      t.y = touch.clientY
    }
  }
})

canvas.addEventListener('touchend', (e) =&gt; {
  for (const touch of e.changedTouches) {
    touches.delete(touch.identifier)
  }
})
</code></pre>
<p>If your game also needs to work with a mouse or stylus, consider Pointer Events (<code>pointerdown</code>/<code>pointermove</code>/<code>pointerup</code>) instead of touch events. MDN now recommends them as the single, device-agnostic input model: one code path handles touch, mouse, and pen, and multi-touch still works through <code>pointerId</code> (the analog of <code>touch.identifier</code> used above). Touch events remain perfectly fine for touch-only games.</p>
<h2>4) Virtual joystick</h2>
<pre><code class="language-js">class VirtualJoystick {
  constructor(x, y, radius) {
    this.baseX = x
    this.baseY = y
    this.radius = radius
    this.knobRadius = radius * 0.4
    this.active = false
    this.touchId = null
    this.dx = 0
    this.dy = 0
  }
  
  handleTouchStart(touch) {
    const dist = Math.hypot(touch.clientX - this.baseX, touch.clientY - this.baseY)
    if (dist &lt; this.radius) {
      this.active = true
      this.touchId = touch.identifier
      this.updatePosition(touch.clientX, touch.clientY)
    }
  }
  
  handleTouchMove(touch) {
    if (touch.identifier === this.touchId) {
      this.updatePosition(touch.clientX, touch.clientY)
    }
  }
  
  handleTouchEnd(touch) {
    if (touch.identifier === this.touchId) {
      this.active = false
      this.touchId = null
      this.dx = 0
      this.dy = 0
    }
  }
  
  updatePosition(x, y) {
    let dx = x - this.baseX
    let dy = y - this.baseY
    const dist = Math.hypot(dx, dy)
    
    if (dist &gt; this.radius) {
      dx = (dx / dist) * this.radius
      dy = (dy / dist) * this.radius
    }
    
    this.dx = dx / this.radius
    this.dy = dy / this.radius
  }
  
  draw(ctx) {
    // Base circle
    ctx.beginPath()
    ctx.arc(this.baseX, this.baseY, this.radius, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'
    ctx.fill()
    
    // Knob
    const knobX = this.baseX + this.dx * this.radius
    const knobY = this.baseY + this.dy * this.radius
    ctx.beginPath()
    ctx.arc(knobX, knobY, this.knobRadius, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'
    ctx.fill()
  }
  
  getInput() {
    return { x: this.dx, y: this.dy }
  }
}
</code></pre>
<h2>5) Touch buttons</h2>
<pre><code class="language-js">class TouchButton {
  constructor(x, y, radius, label) {
    this.x = x
    this.y = y
    this.radius = radius
    this.label = label
    this.pressed = false
    this.touchId = null
  }
  
  contains(px, py) {
    return Math.hypot(px - this.x, py - this.y) &lt; this.radius
  }
  
  handleTouchStart(touch) {
    if (this.contains(touch.clientX, touch.clientY)) {
      this.pressed = true
      this.touchId = touch.identifier
    }
  }
  
  handleTouchEnd(touch) {
    if (touch.identifier === this.touchId) {
      this.pressed = false
      this.touchId = null
    }
  }
  
  draw(ctx) {
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2)
    ctx.fillStyle = this.pressed ? 'rgba(255, 255, 255, 0.5)' : 'rgba(255, 255, 255, 0.2)'
    ctx.fill()
    
    ctx.font = 'bold 24px sans-serif'
    ctx.fillStyle = '#fff'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(this.label, this.x, this.y)
  }
}
</code></pre>
<h2>6) Orientation handling</h2>
<pre><code class="language-js">function checkOrientation() {
  const isLandscape = window.innerWidth &gt; window.innerHeight
  
  if (!isLandscape) {
    showRotatePrompt()
  } else {
    hideRotatePrompt()
    resizeCanvas()
  }
}

window.addEventListener('resize', checkOrientation)
window.addEventListener('orientationchange', checkOrientation)

function showRotatePrompt() {
  document.getElementById('rotate-prompt').style.display = 'flex'
}

function hideRotatePrompt() {
  document.getElementById('rotate-prompt').style.display = 'none'
}
</code></pre>
<h2>7) Performance optimization</h2>
<pre><code class="language-js">// Reduce resolution on low-end devices
function getDeviceScale() {
  const dpr = window.devicePixelRatio || 1
  const isLowEnd = navigator.hardwareConcurrency &lt;= 2
  return isLowEnd ? Math.min(dpr, 1.5) : Math.min(dpr, 2)
}

// Throttle expensive operations
let lastHeavyUpdate = 0
function maybeDoHeavyWork(timestamp) {
  if (timestamp - lastHeavyUpdate &gt; 100) { // 10 fps for heavy stuff
    doExpensiveCalculations()
    lastHeavyUpdate = timestamp
  }
}

// Use lower quality assets
function getAssetQuality() {
  const memory = navigator.deviceMemory || 4
  if (memory &lt;= 2) return 'low'
  if (memory &lt;= 4) return 'medium'
  return 'high'
}
</code></pre>
<h2>8) Battery considerations</h2>
<pre><code class="language-js">// Check battery and reduce effects
async function checkBattery() {
  if ('getBattery' in navigator) {
    const battery = await navigator.getBattery()
    
    if (battery.level &lt; 0.2 &amp;&amp; !battery.charging) {
      enableBatterySaver()
    }
    
    battery.addEventListener('levelchange', () =&gt; {
      if (battery.level &lt; 0.2 &amp;&amp; !battery.charging) {
        enableBatterySaver()
      }
    })
  }
}

function enableBatterySaver() {
  game.particleCount = Math.floor(game.particleCount * 0.5)
  game.targetFps = 30
  console.log('Battery saver enabled')
}
</code></pre>
<h2>9) Fullscreen API</h2>
<pre><code class="language-js">async function requestFullscreen() {
  const elem = document.documentElement
  
  try {
    if (elem.requestFullscreen) {
      await elem.requestFullscreen()
    } else if (elem.webkitRequestFullscreen) {
      await elem.webkitRequestFullscreen()
    }
    
    // Lock orientation
    if (screen.orientation?.lock) {
      await screen.orientation.lock('landscape')
    }
  } catch (err) {
    console.warn('Fullscreen failed:', err)
  }
}

// Call on user interaction
document.getElementById('play-btn').addEventListener('click', () =&gt; {
  requestFullscreen()
  startGame()
})
</code></pre>
<p>One caveat: the Fullscreen API doesn't work for general elements on iPhone. iOS Safari only exposes fullscreen for native video elements (via the non-standard <code>webkitEnterFullscreen</code>), so <code>documentElement.requestFullscreen()</code> will reject on iPhone. The <code>try/catch</code> above handles that gracefully, so design your game to be playable without true fullscreen on iPhone and treat fullscreen as an enhancement on iPad, Android, and desktop where it's supported. The <code>screen.orientation.lock()</code> call has the same limitation on iPhone, so don't depend on it.</p>
<h2>10) Testing checklist</h2>
<p>Before shipping:</p>
<ul>
<li><strong>Touch responsiveness</strong> — Test on actual devices, not just emulators</li>
<li><strong>Various screen sizes</strong> — Phone, tablet, iPad Pro</li>
<li><strong>Both orientations</strong> — Or lock to one</li>
<li><strong>Low-end devices</strong> — Test on 2-3 year old phones</li>
<li><strong>Slow networks</strong> — Test on 3G simulation</li>
<li><strong>Safari iOS</strong> — Has quirks with audio, fullscreen</li>
<li><strong>Chrome Android</strong> — Most common browser</li>
<li><strong>Interruptions</strong> — Phone calls, notifications</li>
<li><strong>Memory pressure</strong> — Does it recover after background tab?</li>
</ul>
<pre><code class="language-js">// Debug touch visualization
function drawTouchDebug(ctx) {
  for (const [id, touch] of touches) {
    ctx.beginPath()
    ctx.arc(touch.x, touch.y, 30, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'
    ctx.fill()
    ctx.fillStyle = '#fff'
    ctx.fillText(id.toString(), touch.x, touch.y)
  }
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/game-input-handling">Game input handling</a></li>
<li><a href="/tutorials/responsive-game-canvas">Responsive game canvas</a></li>
<li><a href="/tutorials/pwa-offline-games">PWA for offline games</a></li>
<li><a href="/tutorials/web-audio-api-games">Web Audio API for games</a> — handling iOS audio restrictions</li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a> — optimizing load times for mobile connections</li>
<li><a href="/tutorials/iframe-embedding-games">Iframe embedding games</a> — mobile-specific embed considerations</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Touch_events">MDN: Touch events</a> — multi-touch handling</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API">MDN: Screen Orientation API</a> — locking orientation</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API">MDN: Fullscreen API</a> — entering fullscreen on mobile</li>
<li><a href="https://web.dev/learn/design/">web.dev: Responsive design</a> — responsive patterns that apply to game UI</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pixel art rendering in web games]]></title>
            <link>https://app.cinevva.com/tutorials/pixel-art-rendering</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/pixel-art-rendering</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Render pixel art correctly: crisp scaling, no blur, color palettes, and animation. Make your retro game look intentional.]]></description>
            <content:encoded><![CDATA[<h1>Pixel art rendering in web games</h1>
<p>Pixel art looks amazing when rendered correctly—and terrible when it's blurry. This tutorial covers the techniques for crisp, authentic pixel graphics.</p>
<h2>1) The blur problem</h2>
<p>By default, browsers smooth images when scaling. For pixel art, this is wrong:</p>
<pre><code class="language-css">/* CSS solution */
canvas {
  image-rendering: pixelated;
  image-rendering: crisp-edges; /* Firefox fallback */
}
</code></pre>
<h2>2) Canvas context settings</h2>
<pre><code class="language-js">const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

// Disable smoothing for crisp pixels
ctx.imageSmoothingEnabled = false
</code></pre>
<p>This must be set after every canvas resize or context change.</p>
<h2>3) Integer scaling</h2>
<p>Pixel art looks best at integer scales (1x, 2x, 3x, 4x):</p>
<pre><code class="language-js">const GAME_WIDTH = 160
const GAME_HEIGHT = 144 // Game Boy resolution

function resize() {
  const maxScale = Math.floor(Math.min(
    window.innerWidth / GAME_WIDTH,
    window.innerHeight / GAME_HEIGHT
  ))
  const scale = Math.max(1, maxScale)
  
  canvas.width = GAME_WIDTH
  canvas.height = GAME_HEIGHT
  canvas.style.width = GAME_WIDTH * scale + 'px'
  canvas.style.height = GAME_HEIGHT * scale + 'px'
  
  ctx.imageSmoothingEnabled = false
}
</code></pre>
<h2>4) Drawing sprites at integer positions</h2>
<p>Sub-pixel positions cause blur:</p>
<pre><code class="language-js">// Bad: causes blur
ctx.drawImage(sprite, 10.5, 20.3)

// Good: crisp pixels
ctx.drawImage(sprite, Math.floor(10.5), Math.floor(20.3))

// Or round to nearest
ctx.drawImage(sprite, Math.round(player.x), Math.round(player.y))
</code></pre>
<h2>5) Sprite sheet animation</h2>
<pre><code class="language-js">class PixelSprite {
  constructor(image, frameWidth, frameHeight) {
    this.image = image
    this.frameWidth = frameWidth
    this.frameHeight = frameHeight
    this.animations = {}
    this.currentAnim = null
    this.frame = 0
    this.timer = 0
  }
  
  addAnimation(name, frames, fps = 8) {
    this.animations[name] = { frames, duration: 1 / fps }
  }
  
  play(name) {
    if (this.currentAnim !== name) {
      this.currentAnim = name
      this.frame = 0
      this.timer = 0
    }
  }
  
  update(dt) {
    if (!this.currentAnim) return
    
    const anim = this.animations[this.currentAnim]
    this.timer += dt
    
    if (this.timer &gt;= anim.duration) {
      this.timer = 0
      this.frame = (this.frame + 1) % anim.frames.length
    }
  }
  
  draw(ctx, x, y, flipX = false) {
    if (!this.currentAnim) return
    
    const anim = this.animations[this.currentAnim]
    const frameIndex = anim.frames[this.frame]
    const sx = (frameIndex % 16) * this.frameWidth
    const sy = Math.floor(frameIndex / 16) * this.frameHeight
    
    ctx.save()
    if (flipX) {
      ctx.scale(-1, 1)
      x = -x - this.frameWidth
    }
    
    ctx.drawImage(
      this.image,
      sx, sy, this.frameWidth, this.frameHeight,
      Math.round(x), Math.round(y), this.frameWidth, this.frameHeight
    )
    ctx.restore()
  }
}

// Usage
const player = new PixelSprite(spriteSheet, 16, 16)
player.addAnimation('idle', [0, 1], 2)
player.addAnimation('walk', [2, 3, 4, 5], 8)
player.addAnimation('jump', [6], 1)
</code></pre>
<h2>6) Palette swapping</h2>
<p>Classic technique for recoloring sprites:</p>
<pre><code class="language-js">function createPaletteSwap(image, oldColors, newColors) {
  const canvas = document.createElement('canvas')
  canvas.width = image.width
  canvas.height = image.height
  const ctx = canvas.getContext('2d')
  
  ctx.drawImage(image, 0, 0)
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  const data = imageData.data
  
  for (let i = 0; i &lt; data.length; i += 4) {
    const r = data[i], g = data[i + 1], b = data[i + 2]
    
    for (let j = 0; j &lt; oldColors.length; j++) {
      const old = oldColors[j]
      if (r === old.r &amp;&amp; g === old.g &amp;&amp; b === old.b) {
        const newC = newColors[j]
        data[i] = newC.r
        data[i + 1] = newC.g
        data[i + 2] = newC.b
        break
      }
    }
  }
  
  ctx.putImageData(imageData, 0, 0)
  return canvas
}

// Create enemy variant
const blueEnemy = createPaletteSwap(
  enemySprite,
  [{ r: 255, g: 0, b: 0 }],    // Red
  [{ r: 0, g: 100, b: 255 }]   // Blue
)
</code></pre>
<h2>7) Tilemap rendering</h2>
<pre><code class="language-js">class Tilemap {
  constructor(tileSize, tilesetImage) {
    this.tileSize = tileSize
    this.tileset = tilesetImage
    this.tilesPerRow = Math.floor(tilesetImage.width / tileSize)
    this.data = []
  }
  
  setData(width, height, tiles) {
    this.width = width
    this.height = height
    this.data = tiles
  }
  
  draw(ctx, cameraX = 0, cameraY = 0) {
    const startCol = Math.floor(cameraX / this.tileSize)
    const startRow = Math.floor(cameraY / this.tileSize)
    const endCol = startCol + Math.ceil(ctx.canvas.width / this.tileSize) + 1
    const endRow = startRow + Math.ceil(ctx.canvas.height / this.tileSize) + 1
    
    for (let row = startRow; row &lt; endRow; row++) {
      for (let col = startCol; col &lt; endCol; col++) {
        if (row &lt; 0 || row &gt;= this.height || col &lt; 0 || col &gt;= this.width) continue
        
        const tileIndex = this.data[row * this.width + col]
        if (tileIndex &lt; 0) continue
        
        const sx = (tileIndex % this.tilesPerRow) * this.tileSize
        const sy = Math.floor(tileIndex / this.tilesPerRow) * this.tileSize
        const dx = Math.round(col * this.tileSize - cameraX)
        const dy = Math.round(row * this.tileSize - cameraY)
        
        ctx.drawImage(
          this.tileset,
          sx, sy, this.tileSize, this.tileSize,
          dx, dy, this.tileSize, this.tileSize
        )
      }
    }
  }
}
</code></pre>
<h2>8) Outline effects</h2>
<p>Add outlines to sprites for visibility:</p>
<pre><code class="language-js">function drawWithOutline(ctx, image, x, y, outlineColor = '#000') {
  const offsets = [[-1, 0], [1, 0], [0, -1], [0, 1]]
  
  // Draw outline
  ctx.globalCompositeOperation = 'source-over'
  for (const [ox, oy] of offsets) {
    ctx.drawImage(image, Math.round(x + ox), Math.round(y + oy))
  }
  
  // Apply color to outline
  ctx.globalCompositeOperation = 'source-in'
  ctx.fillStyle = outlineColor
  ctx.fillRect(x - 1, y - 1, image.width + 2, image.height + 2)
  
  // Draw sprite on top
  ctx.globalCompositeOperation = 'source-over'
  ctx.drawImage(image, Math.round(x), Math.round(y))
}
</code></pre>
<h2>9) Screen shake</h2>
<p>Classic game feel effect:</p>
<pre><code class="language-js">const camera = {
  x: 0,
  y: 0,
  shakeIntensity: 0,
  shakeDuration: 0,
  
  shake(intensity, duration) {
    this.shakeIntensity = intensity
    this.shakeDuration = duration
  },
  
  update(dt) {
    if (this.shakeDuration &gt; 0) {
      this.shakeDuration -= dt
    }
  },
  
  getOffset() {
    if (this.shakeDuration &lt;= 0) return { x: 0, y: 0 }
    
    return {
      x: Math.round((Math.random() - 0.5) * 2 * this.shakeIntensity),
      y: Math.round((Math.random() - 0.5) * 2 * this.shakeIntensity),
    }
  }
}

// In render:
function render() {
  const shake = camera.getOffset()
  ctx.save()
  ctx.translate(shake.x, shake.y)
  // Draw everything...
  ctx.restore()
}

// On hit:
camera.shake(4, 0.2) // 4 pixel intensity, 0.2 seconds
</code></pre>
<h2>10) Color palette constraints</h2>
<p>Authentic pixel art uses limited palettes:</p>
<pre><code class="language-js">const PALETTES = {
  gameboy: ['#0f380f', '#306230', '#8bac0f', '#9bbc0f'],
  nes: ['#000000', '#fcfcfc', '#f8f8f8', '#bcbcbc', /* ... */],
  pico8: [
    '#000000', '#1d2b53', '#7e2553', '#008751',
    '#ab5236', '#5f574f', '#c2c3c7', '#fff1e8',
    '#ff004d', '#ffa300', '#ffec27', '#00e436',
    '#29adff', '#83769c', '#ff77a8', '#ffccaa'
  ],
}

function quantizeColor(r, g, b, palette) {
  let minDist = Infinity
  let closest = palette[0]
  
  for (const color of palette) {
    const pr = parseInt(color.slice(1, 3), 16)
    const pg = parseInt(color.slice(3, 5), 16)
    const pb = parseInt(color.slice(5, 7), 16)
    
    const dist = (r - pr) ** 2 + (g - pg) ** 2 + (b - pb) ** 2
    if (dist &lt; minDist) {
      minDist = dist
      closest = color
    }
  }
  
  return closest
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a></li>
<li><a href="/tutorials/responsive-game-canvas">Responsive game canvas</a></li>
<li><a href="/tutorials/streaming-asset-loading">Streaming asset loading</a></li>
<li><a href="/guides/game-assets-guide">Where to Find Free Game Assets</a> — sprite sheets, pixel art packs, and 2D asset sources</li>
<li><a href="/tutorials/text-rendering-games">Text rendering in games</a> — bitmap fonts that match your pixel art style</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointer Lock for FPS games]]></title>
            <link>https://app.cinevva.com/tutorials/pointer-lock-fps</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/pointer-lock-fps</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Implement mouse-look with Pointer Lock API: capturing cursor, handling movement, and building FPS controls for web games.]]></description>
            <content:encoded><![CDATA[<h1>Pointer Lock for FPS games</h1>
<p>The Pointer Lock API captures the mouse cursor, enabling smooth FPS-style camera controls. Essential for first-person and third-person shooters.</p>
<h2>1) Requesting pointer lock</h2>
<p>Pointer lock requires a user gesture:</p>
<pre><code class="language-js">const canvas = document.getElementById('game')

canvas.addEventListener('click', () =&gt; {
  canvas.requestPointerLock()
})
</code></pre>
<h2>Raw mouse input (disable acceleration)</h2>
<p>By default the browser applies the operating system's mouse acceleration to <code>movementX</code>/<code>movementY</code>, so a fast flick and a slow drag over the same distance produce different camera rotation. For FPS aim you usually want the opposite: the same physical distance should always rotate the camera the same amount. Request raw, unaccelerated movement by passing <code>unadjustedMovement: true</code> to <code>requestPointerLock()</code>:</p>
<pre><code class="language-js">canvas.addEventListener('click', async () =&gt; {
  try {
    await canvas.requestPointerLock({ unadjustedMovement: true })
  } catch (err) {
    // unadjustedMovement unsupported here; fall back to OS-adjusted deltas
    await canvas.requestPointerLock()
  }
})
</code></pre>
<p>The modern <code>requestPointerLock()</code> returns a Promise that resolves on success and rejects on failure, which is why the call above is wrapped in <code>try/catch</code>. Chrome and Edge have honored <code>unadjustedMovement</code> since version 88, and Safari supports it since 18.4 (March 2025), which is also the release that fixed <code>requestPointerLock</code> to return a Promise. Older browsers that don't return a Promise still work here because <code>await</code> tolerates a non-Promise value and the unknown option is simply ignored, so always keep the plain <code>requestPointerLock()</code> fallback.</p>
<h2>2) Detecting lock state</h2>
<pre><code class="language-js">document.addEventListener('pointerlockchange', () =&gt; {
  if (document.pointerLockElement === canvas) {
    console.log('Pointer locked')
    game.mouseLocked = true
  } else {
    console.log('Pointer unlocked')
    game.mouseLocked = false
  }
})

document.addEventListener('pointerlockerror', () =&gt; {
  console.error('Pointer lock failed')
})
</code></pre>
<h2>3) Reading mouse movement</h2>
<p>When locked, use <code>movementX</code> and <code>movementY</code>:</p>
<pre><code class="language-js">document.addEventListener('mousemove', (e) =&gt; {
  if (document.pointerLockElement !== canvas) return
  
  const sensitivity = 0.002
  camera.yaw -= e.movementX * sensitivity
  camera.pitch -= e.movementY * sensitivity
  
  // Clamp pitch to prevent flipping
  camera.pitch = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, camera.pitch))
})
</code></pre>
<h2>4) FPS camera class</h2>
<pre><code class="language-js">class FPSCamera {
  constructor() {
    this.position = { x: 0, y: 1.7, z: 0 } // Eye height
    this.yaw = 0      // Left/right rotation
    this.pitch = 0    // Up/down rotation
    this.sensitivity = 0.002
  }
  
  handleMouseMove(e) {
    this.yaw -= e.movementX * this.sensitivity
    this.pitch -= e.movementY * this.sensitivity
    this.pitch = Math.max(-Math.PI / 2 + 0.01, Math.min(Math.PI / 2 - 0.01, this.pitch))
  }
  
  getForward() {
    return {
      x: Math.sin(this.yaw) * Math.cos(this.pitch),
      y: Math.sin(this.pitch),
      z: Math.cos(this.yaw) * Math.cos(this.pitch),
    }
  }
  
  getRight() {
    return {
      x: Math.cos(this.yaw),
      y: 0,
      z: -Math.sin(this.yaw),
    }
  }
  
  move(forward, right, dt, speed = 5) {
    const fwd = this.getForward()
    const rgt = this.getRight()
    
    // Move on XZ plane only
    this.position.x += (fwd.x * forward + rgt.x * right) * speed * dt
    this.position.z += (fwd.z * forward + rgt.z * right) * speed * dt
  }
  
  getViewMatrix() {
    const forward = this.getForward()
    const target = {
      x: this.position.x + forward.x,
      y: this.position.y + forward.y,
      z: this.position.z + forward.z,
    }
    return lookAt(this.position, target, { x: 0, y: 1, z: 0 })
  }
}
</code></pre>
<h2>5) WASD movement</h2>
<pre><code class="language-js">const input = {
  forward: false,
  backward: false,
  left: false,
  right: false,
  jump: false,
}

window.addEventListener('keydown', (e) =&gt; {
  switch (e.code) {
    case 'KeyW': input.forward = true; break
    case 'KeyS': input.backward = true; break
    case 'KeyA': input.left = true; break
    case 'KeyD': input.right = true; break
    case 'Space': input.jump = true; break
  }
})

window.addEventListener('keyup', (e) =&gt; {
  switch (e.code) {
    case 'KeyW': input.forward = false; break
    case 'KeyS': input.backward = false; break
    case 'KeyA': input.left = false; break
    case 'KeyD': input.right = false; break
    case 'Space': input.jump = false; break
  }
})

function update(dt) {
  const moveForward = (input.forward ? 1 : 0) - (input.backward ? 1 : 0)
  const moveRight = (input.right ? 1 : 0) - (input.left ? 1 : 0)
  
  camera.move(moveForward, moveRight, dt)
}
</code></pre>
<h2>6) Complete FPS controller</h2>
<pre><code class="language-js">class FPSController {
  constructor(canvas) {
    this.canvas = canvas
    this.camera = new FPSCamera()
    this.locked = false
    this.speed = 5
    this.sprintMultiplier = 1.5
    
    this.input = {
      forward: false, backward: false,
      left: false, right: false,
      jump: false, sprint: false,
    }
    
    this.velocity = { x: 0, y: 0, z: 0 }
    this.onGround = true
    this.gravity = -20
    this.jumpSpeed = 8
    
    this.bindEvents()
  }
  
  bindEvents() {
    this.canvas.addEventListener('click', () =&gt; {
      this.canvas.requestPointerLock()
    })
    
    document.addEventListener('pointerlockchange', () =&gt; {
      this.locked = document.pointerLockElement === this.canvas
    })
    
    document.addEventListener('mousemove', (e) =&gt; {
      if (this.locked) {
        this.camera.handleMouseMove(e)
      }
    })
    
    window.addEventListener('keydown', (e) =&gt; this.handleKey(e.code, true))
    window.addEventListener('keyup', (e) =&gt; this.handleKey(e.code, false))
  }
  
  handleKey(code, pressed) {
    switch (code) {
      case 'KeyW': this.input.forward = pressed; break
      case 'KeyS': this.input.backward = pressed; break
      case 'KeyA': this.input.left = pressed; break
      case 'KeyD': this.input.right = pressed; break
      case 'Space': this.input.jump = pressed; break
      case 'ShiftLeft': this.input.sprint = pressed; break
    }
  }
  
  update(dt) {
    if (!this.locked) return
    
    const speed = this.speed * (this.input.sprint ? this.sprintMultiplier : 1)
    
    // Horizontal movement
    const moveForward = (this.input.forward ? 1 : 0) - (this.input.backward ? 1 : 0)
    const moveRight = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0)
    
    const forward = this.camera.getForward()
    const right = this.camera.getRight()
    
    this.velocity.x = (forward.x * moveForward + right.x * moveRight) * speed
    this.velocity.z = (forward.z * moveForward + right.z * moveRight) * speed
    
    // Jumping
    if (this.input.jump &amp;&amp; this.onGround) {
      this.velocity.y = this.jumpSpeed
      this.onGround = false
    }
    
    // Gravity
    if (!this.onGround) {
      this.velocity.y += this.gravity * dt
    }
    
    // Apply velocity
    this.camera.position.x += this.velocity.x * dt
    this.camera.position.y += this.velocity.y * dt
    this.camera.position.z += this.velocity.z * dt
    
    // Simple ground collision
    if (this.camera.position.y &lt; 1.7) {
      this.camera.position.y = 1.7
      this.velocity.y = 0
      this.onGround = true
    }
  }
}
</code></pre>
<h2>7) Crosshair</h2>
<pre><code class="language-js">function drawCrosshair(ctx) {
  const cx = ctx.canvas.width / 2
  const cy = ctx.canvas.height / 2
  const size = 10
  const gap = 4
  
  ctx.strokeStyle = '#fff'
  ctx.lineWidth = 2
  
  // Top
  ctx.beginPath()
  ctx.moveTo(cx, cy - gap)
  ctx.lineTo(cx, cy - gap - size)
  ctx.stroke()
  
  // Bottom
  ctx.beginPath()
  ctx.moveTo(cx, cy + gap)
  ctx.lineTo(cx, cy + gap + size)
  ctx.stroke()
  
  // Left
  ctx.beginPath()
  ctx.moveTo(cx - gap, cy)
  ctx.lineTo(cx - gap - size, cy)
  ctx.stroke()
  
  // Right
  ctx.beginPath()
  ctx.moveTo(cx + gap, cy)
  ctx.lineTo(cx + gap + size, cy)
  ctx.stroke()
}
</code></pre>
<h2>8) Shooting with mouse buttons</h2>
<pre><code class="language-js">document.addEventListener('mousedown', (e) =&gt; {
  if (!document.pointerLockElement) return
  
  if (e.button === 0) {
    // Left click - primary fire
    weapon.fire()
  } else if (e.button === 2) {
    // Right click - aim down sights
    weapon.aimDownSights(true)
  }
})

document.addEventListener('mouseup', (e) =&gt; {
  if (e.button === 2) {
    weapon.aimDownSights(false)
  }
})

// Prevent context menu
canvas.addEventListener('contextmenu', (e) =&gt; e.preventDefault())
</code></pre>
<h2>9) Sensitivity settings</h2>
<pre><code class="language-js">class Settings {
  constructor() {
    this.mouseSensitivity = parseFloat(localStorage.getItem('sensitivity') || '1.0')
    this.invertY = localStorage.getItem('invertY') === 'true'
  }
  
  save() {
    localStorage.setItem('sensitivity', this.mouseSensitivity.toString())
    localStorage.setItem('invertY', this.invertY.toString())
  }
}

// Apply in mouse handler
document.addEventListener('mousemove', (e) =&gt; {
  if (!locked) return
  
  const sens = settings.mouseSensitivity * 0.002
  camera.yaw -= e.movementX * sens
  camera.pitch -= e.movementY * sens * (settings.invertY ? -1 : 1)
})
</code></pre>
<h2>10) Exit prompt</h2>
<p>Show instructions for exiting pointer lock:</p>
<pre><code class="language-js">function showLockUI() {
  const ui = document.getElementById('lock-ui')
  
  if (document.pointerLockElement) {
    ui.innerHTML = '&lt;p&gt;Press ESC to unlock mouse&lt;/p&gt;'
    ui.style.opacity = '0.5'
    setTimeout(() =&gt; ui.style.opacity = '0', 2000)
  } else {
    ui.innerHTML = '&lt;p&gt;Click to play&lt;/p&gt;'
    ui.style.opacity = '1'
  }
}

document.addEventListener('pointerlockchange', showLockUI)
</code></pre>
<p>One thing to know about the exit prompt: when the player presses ESC to leave pointer lock, the browser requires a fresh user gesture (a click) before you can re-lock, which is why the 'Click to play' overlay exists. But if your own code calls <code>document.exitPointerLock()</code> (for example to open an in-game menu), no new gesture is needed to re-lock afterward, so you can re-engage programmatically when the menu closes. Repeatedly hitting ESC can also signal the browser to refuse re-locking until a more deliberate user action, so don't try to auto-relock on <code>pointerlockchange</code>.</p>
<h2>Iframe considerations</h2>
<p>Pointer lock in iframes requires the <code>allow=&quot;pointer-lock&quot;</code> attribute:</p>
<pre><code class="language-html">&lt;iframe 
  src=&quot;game.html&quot; 
  allow=&quot;pointer-lock; fullscreen&quot;
&gt;&lt;/iframe&gt;
</code></pre>
<p>Check if pointer lock is available:</p>
<pre><code class="language-js">if (!document.pointerLockElement &amp;&amp; !('requestPointerLock' in canvas)) {
  showMessage('Mouse capture not available')
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/game-input-handling">Game input handling</a></li>
<li><a href="/tutorials/gamepad-api">Gamepad API</a></li>
<li><a href="/tutorials/webgl-fundamentals-for-games">WebGL fundamentals</a></li>
<li><a href="/tutorials/webxr-basics">WebXR basics</a> — VR controls for first-person experiences</li>
<li><a href="/tutorials/webgpu-getting-started">WebGPU getting started</a> — modern GPU rendering for FPS games</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API">MDN: Pointer Lock API</a> — full API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX">MDN: MouseEvent.movementX</a> — reading mouse deltas</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PWA for offline web games]]></title>
            <link>https://app.cinevva.com/tutorials/pwa-offline-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/pwa-offline-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Make your game work offline with PWA: manifest, service worker, caching strategies, and install prompts. Play anywhere, anytime.]]></description>
            <content:encoded><![CDATA[<h1>PWA for offline web games</h1>
<p>Progressive Web Apps let players install your game and play offline. This tutorial shows how to add PWA support to a web game.</p>
<h2>1) Web App Manifest</h2>
<p>Create <code>manifest.json</code>:</p>
<pre><code class="language-json">{
  &quot;name&quot;: &quot;My Awesome Game&quot;,
  &quot;short_name&quot;: &quot;AwesomeGame&quot;,
  &quot;description&quot;: &quot;An awesome game you can play offline&quot;,
  &quot;start_url&quot;: &quot;/&quot;,
  &quot;display&quot;: &quot;fullscreen&quot;,
  &quot;orientation&quot;: &quot;landscape&quot;,
  &quot;background_color&quot;: &quot;#1a1a2e&quot;,
  &quot;theme_color&quot;: &quot;#4ade80&quot;,
  &quot;icons&quot;: [
    {
      &quot;src&quot;: &quot;/icons/icon-192.png&quot;,
      &quot;sizes&quot;: &quot;192x192&quot;,
      &quot;type&quot;: &quot;image/png&quot;
    },
    {
      &quot;src&quot;: &quot;/icons/icon-512.png&quot;,
      &quot;sizes&quot;: &quot;512x512&quot;,
      &quot;type&quot;: &quot;image/png&quot;
    },
    {
      &quot;src&quot;: &quot;/icons/icon-maskable.png&quot;,
      &quot;sizes&quot;: &quot;512x512&quot;,
      &quot;type&quot;: &quot;image/png&quot;,
      &quot;purpose&quot;: &quot;maskable&quot;
    }
  ]
}
</code></pre>
<p>Link it in your HTML:</p>
<pre><code class="language-html">&lt;link rel=&quot;manifest&quot; href=&quot;/manifest.json&quot;&gt;
&lt;meta name=&quot;theme-color&quot; content=&quot;#4ade80&quot;&gt;
&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;/icons/icon-192.png&quot;&gt;
</code></pre>
<h2>2) Basic service worker</h2>
<p>Create <code>sw.js</code>:</p>
<pre><code class="language-js">const CACHE_NAME = 'game-v1'

const ASSETS = [
  '/',
  '/index.html',
  '/game.js',
  '/style.css',
  '/assets/sprites.png',
  '/assets/sounds/jump.mp3',
  '/assets/sounds/music.mp3',
]

// Install: cache assets
self.addEventListener('install', (event) =&gt; {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) =&gt; {
      return cache.addAll(ASSETS)
    })
  )
})

// Activate: clean old caches
self.addEventListener('activate', (event) =&gt; {
  event.waitUntil(
    caches.keys().then((keys) =&gt; {
      return Promise.all(
        keys.filter(key =&gt; key !== CACHE_NAME)
            .map(key =&gt; caches.delete(key))
      )
    })
  )
})

// Fetch: serve from cache, fall back to network
self.addEventListener('fetch', (event) =&gt; {
  event.respondWith(
    caches.match(event.request).then((cached) =&gt; {
      return cached || fetch(event.request)
    })
  )
})
</code></pre>
<h2>3) Register the service worker</h2>
<pre><code class="language-js">if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () =&gt; {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js')
      console.log('SW registered:', registration.scope)
    } catch (err) {
      console.error('SW registration failed:', err)
    }
  })
}
</code></pre>
<h2>4) Cache-first with network update</h2>
<p>Better for games—fast loading with background updates:</p>
<pre><code class="language-js">self.addEventListener('fetch', (event) =&gt; {
  event.respondWith(
    caches.open(CACHE_NAME).then(async (cache) =&gt; {
      const cached = await cache.match(event.request)
      
      // Start network fetch in background
      const fetchPromise = fetch(event.request).then((response) =&gt; {
        if (response.ok) {
          cache.put(event.request, response.clone())
        }
        return response
      }).catch(() =&gt; null)
      
      // Return cached immediately, or wait for network
      return cached || fetchPromise
    })
  )
})
</code></pre>
<h2>5) Versioned cache for updates</h2>
<pre><code class="language-js">const CACHE_VERSION = 'v2'
const STATIC_CACHE = `static-${CACHE_VERSION}`
const DYNAMIC_CACHE = `dynamic-${CACHE_VERSION}`

const STATIC_ASSETS = [
  '/',
  '/index.html',
  '/game.js',
  // ... core assets that rarely change
]

self.addEventListener('install', (event) =&gt; {
  self.skipWaiting() // Activate immediately
  
  event.waitUntil(
    caches.open(STATIC_CACHE).then(cache =&gt; cache.addAll(STATIC_ASSETS))
  )
})

self.addEventListener('activate', (event) =&gt; {
  event.waitUntil(
    caches.keys().then(keys =&gt; {
      return Promise.all(
        keys.filter(key =&gt; !key.includes(CACHE_VERSION))
            .map(key =&gt; caches.delete(key))
      )
    })
  )
  
  clients.claim() // Take control immediately
})
</code></pre>
<h2>6) Handling game updates</h2>
<p>Notify players when an update is available:</p>
<pre><code class="language-js">// In main app
let refreshing = false

navigator.serviceWorker.addEventListener('controllerchange', () =&gt; {
  if (!refreshing) {
    refreshing = true
    showUpdateNotification()
  }
})

function showUpdateNotification() {
  const banner = document.createElement('div')
  banner.innerHTML = `
    &lt;p&gt;Game updated! Refresh to get the latest version.&lt;/p&gt;
    &lt;button onclick=&quot;location.reload()&quot;&gt;Refresh&lt;/button&gt;
  `
  banner.className = 'update-banner'
  document.body.appendChild(banner)
}
</code></pre>
<h2>7) Offline detection</h2>
<pre><code class="language-js">function updateOnlineStatus() {
  if (navigator.onLine) {
    hideOfflineBanner()
    syncGameData()
  } else {
    showOfflineBanner()
  }
}

window.addEventListener('online', updateOnlineStatus)
window.addEventListener('offline', updateOnlineStatus)

function showOfflineBanner() {
  document.getElementById('offline-banner').style.display = 'block'
}

function hideOfflineBanner() {
  document.getElementById('offline-banner').style.display = 'none'
}
</code></pre>
<h2>8) Install prompt</h2>
<pre><code class="language-js">let deferredPrompt = null

window.addEventListener('beforeinstallprompt', (e) =&gt; {
  e.preventDefault()
  deferredPrompt = e
  showInstallButton()
})

function showInstallButton() {
  const btn = document.getElementById('install-btn')
  btn.style.display = 'block'
  btn.addEventListener('click', installApp)
}

async function installApp() {
  if (!deferredPrompt) return
  
  deferredPrompt.prompt()
  const { outcome } = await deferredPrompt.userChoice
  
  console.log('Install prompt outcome:', outcome)
  deferredPrompt = null
  document.getElementById('install-btn').style.display = 'none'
}

window.addEventListener('appinstalled', () =&gt; {
  console.log('App installed!')
  deferredPrompt = null
})
</code></pre>
<p>On iOS and iPadOS, the <code>beforeinstallprompt</code> event never fires, so the install button above only shows up in Chromium browsers. iPhone and iPad users install by tapping Share then &quot;Add to Home Screen.&quot; One thing changed in 2026 worth knowing: starting with Safari 26 (iOS 26 / iPadOS 26), every site added to the Home Screen opens as a web app by default, with an &quot;Open as Web App&quot; toggle that's on by default. There's no longer an installability requirement on iOS, though shipping a manifest and service worker still gives you a far better offline experience.</p>
<h2>9) Background sync for leaderboards</h2>
<p>Heads up on support: the Background Sync API is only implemented in Chromium browsers (Chrome, Edge, Opera, Samsung Internet). Firefox and Safari (including iOS) don't support it, so always feature-detect and keep a fallback that submits scores on the next normal app load.</p>
<pre><code class="language-js">// In service worker
self.addEventListener('sync', (event) =&gt; {
  if (event.tag === 'sync-scores') {
    event.waitUntil(syncScores())
  }
})

async function syncScores() {
  const db = await openDB('game', 1)
  const pendingScores = await db.getAll('pending-scores')
  
  for (const score of pendingScores) {
    try {
      await fetch('/api/scores', {
        method: 'POST',
        body: JSON.stringify(score),
        headers: { 'Content-Type': 'application/json' }
      })
      await db.delete('pending-scores', score.id)
    } catch (err) {
      // Will retry on next sync
      break
    }
  }
}

// In main app
async function submitScore(score) {
  try {
    await fetch('/api/scores', { method: 'POST', body: JSON.stringify(score) })
  } catch {
    // Save for later sync
    const db = await openDB('game', 1)
    await db.add('pending-scores', { ...score, id: Date.now() })
    
    if ('serviceWorker' in navigator &amp;&amp; 'sync' in window.registration) {
      await navigator.serviceWorker.ready
      await registration.sync.register('sync-scores')
    }
  }
}
</code></pre>
<h2>10) Testing PWA</h2>
<p><strong>Chrome DevTools:</strong></p>
<ul>
<li>Application &gt; Service Workers</li>
<li>Application &gt; Manifest</li>
<li>Application &gt; Cache Storage</li>
<li>Network &gt; Offline checkbox</li>
</ul>
<p><strong>Lighthouse audit:</strong></p>
<ul>
<li>Run PWA audit</li>
<li>Check installability</li>
<li>Check offline capability</li>
</ul>
<p><strong>Real device testing:</strong></p>
<ul>
<li>Install on phone home screen</li>
<li>Enable airplane mode</li>
<li>Test all features offline</li>
</ul>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/service-workers-caching">Service workers for game caching</a></li>
<li><a href="/tutorials/indexeddb-game-saves">IndexedDB game saves</a></li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a> — touch controls and viewport handling for PWA games</li>
<li><a href="/tutorials/streaming-asset-loading">Streaming asset loading</a> — loading strategies that work with service worker caching</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps">MDN: Progressive Web Apps</a> — full PWA documentation</li>
<li><a href="https://web.dev/learn/pwa/">web.dev: Learn PWA</a> — Google's PWA learning path</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/Manifest">MDN: Web App Manifest</a> — manifest file reference</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive game canvas that scales properly]]></title>
            <link>https://app.cinevva.com/tutorials/responsive-game-canvas</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/responsive-game-canvas</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Make your game canvas responsive: pixel-perfect scaling, letterboxing, and handling resize events without jank.]]></description>
            <content:encoded><![CDATA[<h1>Responsive Game Canvas</h1>
<p>A canvas that doesn't scale properly looks blurry or breaks on different screen sizes. I've debugged this issue more times than I can count, so let me save you the trouble.</p>
<p><strong>Try different scaling modes:</strong></p>
<ResponsiveDemo />
<h2>The Core Problem</h2>
<p>Canvas has two sizes that are easy to confuse. The CSS size controls how big it appears on screen. The internal resolution controls how many pixels you're actually drawing. If these don't match, you get blur or distortion.</p>
<p>On a Retina display, your CSS might say 800x600, but the screen actually has 1600x1200 physical pixels. If your canvas internal resolution is only 800x600, the browser scales it up and everything looks fuzzy.</p>
<h2>Basic Responsive Setup</h2>
<p>Here's how to make a canvas fill the window and look sharp:</p>
<pre><code class="language-js">const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

function resize() {
  const dpr = window.devicePixelRatio || 1
  const width = window.innerWidth
  const height = window.innerHeight
  
  // Set internal resolution to match physical pixels
  canvas.width = width * dpr
  canvas.height = height * dpr
  
  // Set CSS size to match logical pixels
  canvas.style.width = width + 'px'
  canvas.style.height = height + 'px'
  
  // Scale context so you can draw in logical pixels
  ctx.scale(dpr, dpr)
}

window.addEventListener('resize', resize)
resize()
</code></pre>
<p>The <code>ctx.scale(dpr, dpr)</code> line is the trick. After that, you can draw at position (100, 100) and it shows up at the right place regardless of DPR. The canvas internally renders at 200x200 on a 2x display, but your code doesn't need to know that.</p>
<p>One gotcha: <code>ctx.scale</code> is cumulative. If you call resize multiple times, you'll keep scaling up. Either reset the transform first with <code>ctx.setTransform(1, 0, 0, 1, 0, 0)</code> before scaling, or only scale once.</p>
<h2>Fixed Aspect Ratio with Letterboxing</h2>
<p>Many games need a specific aspect ratio. You don't want your 16:9 game stretched to fill a 21:9 ultrawide monitor. Letterboxing adds black bars to preserve the ratio.</p>
<pre><code class="language-js">const GAME_WIDTH = 1920
const GAME_HEIGHT = 1080
const ASPECT = GAME_WIDTH / GAME_HEIGHT

function resizeWithLetterbox() {
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight
  const windowAspect = windowWidth / windowHeight
  
  let width, height
  
  if (windowAspect &gt; ASPECT) {
    // Window is wider than game, add bars on sides
    height = windowHeight
    width = height * ASPECT
  } else {
    // Window is taller than game, add bars on top/bottom
    width = windowWidth
    height = width / ASPECT
  }
  
  canvas.style.width = width + 'px'
  canvas.style.height = height + 'px'
  canvas.style.position = 'absolute'
  canvas.style.left = (windowWidth - width) / 2 + 'px'
  canvas.style.top = (windowHeight - height) / 2 + 'px'
  
  // Internal resolution stays fixed
  canvas.width = GAME_WIDTH
  canvas.height = GAME_HEIGHT
}
</code></pre>
<p>For the letterbox bars to show, set your body background to black:</p>
<pre><code class="language-css">body {
  margin: 0;
  background: #000;
  overflow: hidden;
}
</code></pre>
<h2>Integer Scaling for Pixel Art</h2>
<p>Pixel art looks crisp at integer scales (1x, 2x, 3x) and blurry at fractional scales like 2.7x. Even with <code>image-rendering: pixelated</code>, a 2.5x scale means some pixels are 2 screen pixels wide and others are 3.</p>
<pre><code class="language-js">const GAME_WIDTH = 320
const GAME_HEIGHT = 180

function resizePixelPerfect() {
  const maxWidth = window.innerWidth
  const maxHeight = window.innerHeight
  
  // Find largest integer scale that fits
  const scaleX = Math.floor(maxWidth / GAME_WIDTH)
  const scaleY = Math.floor(maxHeight / GAME_HEIGHT)
  const scale = Math.max(1, Math.min(scaleX, scaleY))
  
  const width = GAME_WIDTH * scale
  const height = GAME_HEIGHT * scale
  
  canvas.width = GAME_WIDTH
  canvas.height = GAME_HEIGHT
  canvas.style.width = width + 'px'
  canvas.style.height = height + 'px'
  canvas.style.imageRendering = 'pixelated'
}
</code></pre>
<p>The trade-off is that your game won't fill the screen exactly. On a 1920x1080 display with a 320x180 game, you get 5x scaling (1600x900) with black bars around the edges. Some players prefer this; others want the game to fill their screen even if it's slightly blurry.</p>
<h2>WebGL Canvas Scaling</h2>
<p>For WebGL, you need to update the viewport in addition to the canvas size:</p>
<pre><code class="language-js">function resizeGL(gl, canvas) {
  const dpr = window.devicePixelRatio || 1
  const width = canvas.clientWidth * dpr
  const height = canvas.clientHeight * dpr
  
  if (canvas.width !== width || canvas.height !== height) {
    canvas.width = width
    canvas.height = height
    gl.viewport(0, 0, width, height)
    return true // Resized, you may need to update projection matrices
  }
  return false
}
</code></pre>
<p>Call this at the start of your render loop, not just on resize events. Some browsers change DPR when you drag a window between monitors, and you want to catch that.</p>
<h2>Debouncing Resize Events</h2>
<p>Resize events fire rapidly while the user drags the window edge. If your resize function is expensive, you'll get jank.</p>
<pre><code class="language-js">let resizeTimeout
window.addEventListener('resize', () =&gt; {
  clearTimeout(resizeTimeout)
  resizeTimeout = setTimeout(resize, 100)
})
</code></pre>
<p>The 100ms delay means the resize only happens after the user stops dragging. For smoother handling during the drag, use ResizeObserver instead:</p>
<pre><code class="language-js">const observer = new ResizeObserver(entries =&gt; {
  resize()
})
observer.observe(document.body)
</code></pre>
<p>ResizeObserver fires less frequently and is better optimized by the browser.</p>
<h2>Fullscreen</h2>
<p>The Fullscreen API lets you take over the whole screen:</p>
<pre><code class="language-js">async function toggleFullscreen() {
  if (!document.fullscreenElement) {
    await canvas.requestFullscreen()
  } else {
    await document.exitFullscreen()
  }
}

document.addEventListener('fullscreenchange', resize)
</code></pre>
<p>You must call <code>requestFullscreen</code> in response to a user gesture like a click. Browsers block it otherwise. And remember to resize when entering/exiting fullscreen since the available space changes.</p>
<p>One platform caveat: as of mid-2026 the Fullscreen API still doesn't cover element fullscreen on iPhone Safari. requestFullscreen works on desktop browsers and on iPadOS, but on iPhone it isn't supported for arbitrary elements like a canvas (only native video fullscreen works). Feature-detect with <code>if (canvas.requestFullscreen)</code> and fall back gracefully, for example by sizing the canvas to fill the visible viewport or prompting users to add the game to their home screen as a PWA.</p>
<h2>Putting It Together</h2>
<p>Here's a class that handles all the common cases:</p>
<pre><code class="language-js">class ResponsiveCanvas {
  constructor(canvas, options = {}) {
    this.canvas = canvas
    this.ctx = canvas.getContext('2d')
    this.gameWidth = options.width || 1280
    this.gameHeight = options.height || 720
    this.pixelArt = options.pixelArt || false
    this.letterbox = options.letterbox !== false
    
    this.bind()
    this.resize()
  }
  
  bind() {
    window.addEventListener('resize', () =&gt; this.resize())
    document.addEventListener('fullscreenchange', () =&gt; this.resize())
  }
  
  resize() {
    const aspect = this.gameWidth / this.gameHeight
    let width = window.innerWidth
    let height = window.innerHeight
    
    if (this.letterbox) {
      if (width / height &gt; aspect) {
        width = height * aspect
      } else {
        height = width / aspect
      }
    }
    
    if (this.pixelArt) {
      const scale = Math.max(1, Math.floor(Math.min(
        window.innerWidth / this.gameWidth,
        window.innerHeight / this.gameHeight
      )))
      width = this.gameWidth * scale
      height = this.gameHeight * scale
    }
    
    this.canvas.width = this.gameWidth
    this.canvas.height = this.gameHeight
    this.canvas.style.width = width + 'px'
    this.canvas.style.height = height + 'px'
    this.canvas.style.position = 'absolute'
    this.canvas.style.left = (window.innerWidth - width) / 2 + 'px'
    this.canvas.style.top = (window.innerHeight - height) / 2 + 'px'
    
    if (this.pixelArt) {
      this.canvas.style.imageRendering = 'pixelated'
    }
  }
  
  get width() { return this.gameWidth }
  get height() { return this.gameHeight }
}
</code></pre>
<p>Use it like this:</p>
<pre><code class="language-js">const responsive = new ResponsiveCanvas(document.getElementById('game'), {
  width: 320,
  height: 180,
  pixelArt: true,
  letterbox: true
})

// In your game code, use responsive.width and responsive.height
</code></pre>
<h2>Common Gotchas</h2>
<p>A few things that catch people:</p>
<p><strong>Canvas clears on resize.</strong> When you set <code>canvas.width</code> or <code>canvas.height</code>, the canvas clears. If you're not redrawing every frame, you need to redraw after resize.</p>
<p><strong>DPR can change.</strong> If the user drags the browser window from a Retina display to a non-Retina display, DPR changes. Check it in your render loop, not just on resize.</p>
<p><strong>iOS Safari viewport quirks.</strong> The viewport height changes when the address bar shows/hides. Use <code>window.visualViewport</code> for more accurate sizing on mobile.</p>
<p><strong>Context state resets.</strong> Setting canvas dimensions resets context state including transforms, fill styles, and <code>imageSmoothingEnabled</code>. Reapply them after resize.</p>
<h2>More Resources</h2>
<p><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a> covers the fundamentals of update/render loops.</p>
<p><a href="/tutorials/pixel-art-rendering">Pixel art rendering</a> goes deeper on crisp pixel graphics.</p>
<p><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a> covers touch input and viewport issues.</p>
<p><a href="/tutorials/webgl-fundamentals-for-games">WebGL fundamentals</a> covers viewport and canvas setup for WebGL contexts.</p>
<p><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a> covers optimizing canvas size for performance.</p>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service workers for game asset caching]]></title>
            <link>https://app.cinevva.com/tutorials/service-workers-caching</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/service-workers-caching</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Cache game assets with service workers: strategies, versioning, and updates. Make your game load instantly on repeat visits.]]></description>
            <content:encoded><![CDATA[<h1>Service workers for game asset caching</h1>
<p>Service workers let you control how assets are cached and served. For games, this means instant loads on repeat visits and offline support.</p>
<h2>1) Service worker basics</h2>
<p>Create <code>sw.js</code> in your root:</p>
<pre><code class="language-js">// sw.js
self.addEventListener('install', (event) =&gt; {
  console.log('Service worker installing')
})

self.addEventListener('activate', (event) =&gt; {
  console.log('Service worker activated')
})

self.addEventListener('fetch', (event) =&gt; {
  // Intercept all network requests
})
</code></pre>
<p>Register it:</p>
<pre><code class="language-js">if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(reg =&gt; console.log('SW registered'))
    .catch(err =&gt; console.error('SW registration failed:', err))
}
</code></pre>
<h2>2) Cache-first strategy (best for game assets)</h2>
<p>Load from cache, only fetch if not cached:</p>
<pre><code class="language-js">const CACHE_NAME = 'game-assets-v1'

self.addEventListener('fetch', (event) =&gt; {
  event.respondWith(
    caches.match(event.request).then((cached) =&gt; {
      if (cached) {
        return cached
      }
      
      return fetch(event.request).then((response) =&gt; {
        // Don't cache non-ok responses or non-GET requests
        if (!response.ok || event.request.method !== 'GET') {
          return response
        }
        
        // Clone response for caching
        const clone = response.clone()
        caches.open(CACHE_NAME).then((cache) =&gt; {
          cache.put(event.request, clone)
        })
        
        return response
      })
    })
  )
})
</code></pre>
<h2>3) Precache critical assets</h2>
<p>Install event is perfect for precaching:</p>
<pre><code class="language-js">const CACHE_NAME = 'game-v1'

const PRECACHE = [
  '/',
  '/index.html',
  '/game.js',
  '/style.css',
  '/assets/sprites.png',
  '/assets/tileset.png',
  '/assets/player.png',
]

self.addEventListener('install', (event) =&gt; {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache =&gt; cache.addAll(PRECACHE))
      .then(() =&gt; self.skipWaiting())
  )
})
</code></pre>
<h2>4) Network-first for dynamic content</h2>
<p>Use network-first for things that change (leaderboards, player data):</p>
<pre><code class="language-js">self.addEventListener('fetch', (event) =&gt; {
  const url = new URL(event.request.url)
  
  // API calls: network first
  if (url.pathname.startsWith('/api/')) {
    event.respondWith(networkFirst(event.request))
    return
  }
  
  // Assets: cache first
  event.respondWith(cacheFirst(event.request))
})

async function networkFirst(request) {
  try {
    const response = await fetch(request)
    const cache = await caches.open('api-cache')
    cache.put(request, response.clone())
    return response
  } catch {
    return caches.match(request)
  }
}

async function cacheFirst(request) {
  const cached = await caches.match(request)
  if (cached) return cached
  
  const response = await fetch(request)
  const cache = await caches.open(CACHE_NAME)
  cache.put(request, response.clone())
  return response
}
</code></pre>
<h2>5) Stale-while-revalidate</h2>
<p>Return cached immediately, update in background:</p>
<pre><code class="language-js">async function staleWhileRevalidate(request) {
  const cache = await caches.open(CACHE_NAME)
  const cached = await cache.match(request)
  
  const fetchPromise = fetch(request).then((response) =&gt; {
    if (response.ok) {
      cache.put(request, response.clone())
    }
    return response
  })
  
  return cached || fetchPromise
}
</code></pre>
<h2>6) Cache versioning and cleanup</h2>
<p>Clean old caches on activate:</p>
<pre><code class="language-js">const CACHE_VERSION = 'v2'
const CACHE_NAME = `game-${CACHE_VERSION}`

self.addEventListener('activate', (event) =&gt; {
  event.waitUntil(
    caches.keys().then((keys) =&gt; {
      return Promise.all(
        keys
          .filter(key =&gt; key.startsWith('game-') &amp;&amp; key !== CACHE_NAME)
          .map(key =&gt; {
            console.log('Deleting old cache:', key)
            return caches.delete(key)
          })
      )
    }).then(() =&gt; self.clients.claim())
  )
})
</code></pre>
<h2>7) Separate caches by type</h2>
<p>Organize caches for better management:</p>
<pre><code class="language-js">const CACHES = {
  static: 'static-v1',    // HTML, JS, CSS
  images: 'images-v1',    // Sprites, textures
  audio: 'audio-v1',      // Music, SFX
  api: 'api-v1',          // API responses
}

self.addEventListener('fetch', (event) =&gt; {
  const url = new URL(event.request.url)
  
  if (url.pathname.match(/\.(png|jpg|webp)$/)) {
    event.respondWith(cacheFirst(event.request, CACHES.images))
  } else if (url.pathname.match(/\.(mp3|ogg|wav)$/)) {
    event.respondWith(cacheFirst(event.request, CACHES.audio))
  } else if (url.pathname.startsWith('/api/')) {
    event.respondWith(networkFirst(event.request, CACHES.api))
  } else {
    event.respondWith(cacheFirst(event.request, CACHES.static))
  }
})
</code></pre>
<h2>8) Range requests for audio/video</h2>
<p>One thing to know up front: the Cache API will not store partial responses. If a 206 Partial Content response ever reaches cache.put(), it throws TypeError: Failed to execute 'put' on 'Cache': Partial response (status code 206) is unsupported. So the pattern for cached media is always the same: precache (or fetch) the full file as a normal 200 response, then build the 206 yourself by slicing the cached bytes whenever a request arrives with a Range header. If you'd rather not hand-roll this, Workbox's range-requests plugin does exactly that slicing for you when paired with a CacheFirst strategy.</p>
<p>Handle range requests properly (needed for audio seeking):</p>
<pre><code class="language-js">self.addEventListener('fetch', (event) =&gt; {
  if (event.request.headers.has('range')) {
    event.respondWith(handleRangeRequest(event.request))
    return
  }
  // ... normal handling
})

async function handleRangeRequest(request) {
  const cache = await caches.open(CACHES.audio)
  // Match the full resource, ignoring the Range header (which would never match a cached full file)
  let cached = await cache.match(request.url)

  if (!cached) {
    // Fetch the FULL file (string URL drops the Range header) and cache it as a 200
    cached = await fetch(request.url)
    if (cached.ok) cache.put(request.url, cached.clone()) // cache.put rejects 206, so only store full 200s
  }

  // Build a 206 Partial Content response from the cached full body
  const rangeHeader = request.headers.get('range') // e.g. &quot;bytes=200-1000&quot;
  const buffer = await cached.arrayBuffer()
  const total = buffer.byteLength
  const [startStr, endStr] = rangeHeader.replace(/bytes=/, '').split('-')
  const start = Number(startStr)
  const end = endStr ? Number(endStr) : total - 1
  const slice = buffer.slice(start, end + 1)

  return new Response(slice, {
    status: 206,
    statusText: 'Partial Content',
    headers: {
      'Content-Type': cached.headers.get('Content-Type') || 'application/octet-stream',
      'Content-Range': `bytes ${start}-${end}/${total}`,
      'Content-Length': String(slice.byteLength),
      'Accept-Ranges': 'bytes',
    },
  })
}
</code></pre>
<h2>9) Update notification</h2>
<p>Tell players when a new version is ready:</p>
<pre><code class="language-js">// In main app
let refreshing = false

navigator.serviceWorker.addEventListener('controllerchange', () =&gt; {
  if (refreshing) return
  refreshing = true
  
  showUpdateBanner()
})

function showUpdateBanner() {
  const banner = document.createElement('div')
  banner.className = 'update-banner'
  banner.innerHTML = `
    &lt;span&gt;New version available!&lt;/span&gt;
    &lt;button onclick=&quot;location.reload()&quot;&gt;Update&lt;/button&gt;
  `
  document.body.appendChild(banner)
}
</code></pre>
<h2>10) Complete game service worker</h2>
<pre><code class="language-js">const VERSION = 'v1'
const STATIC_CACHE = `static-${VERSION}`
const ASSET_CACHE = `assets-${VERSION}`

const PRECACHE_URLS = [
  '/',
  '/index.html',
  '/game.js',
  '/style.css',
]

// Install: precache critical resources
self.addEventListener('install', (event) =&gt; {
  event.waitUntil(
    caches.open(STATIC_CACHE)
      .then(cache =&gt; cache.addAll(PRECACHE_URLS))
      .then(() =&gt; self.skipWaiting())
  )
})

// Activate: clean old caches
self.addEventListener('activate', (event) =&gt; {
  event.waitUntil(
    caches.keys().then(keys =&gt; Promise.all(
      keys
        .filter(key =&gt; !key.endsWith(VERSION))
        .map(key =&gt; caches.delete(key))
    )).then(() =&gt; self.clients.claim())
  )
})

// Fetch: route requests to appropriate strategy
self.addEventListener('fetch', (event) =&gt; {
  const url = new URL(event.request.url)
  
  // Same-origin only
  if (url.origin !== location.origin) {
    return
  }
  
  // API: network first with cache fallback
  if (url.pathname.startsWith('/api/')) {
    event.respondWith(networkFirst(event.request, 'api-cache'))
    return
  }
  
  // Assets: cache first
  if (url.pathname.startsWith('/assets/')) {
    event.respondWith(cacheFirst(event.request, ASSET_CACHE))
    return
  }
  
  // HTML/JS/CSS: stale while revalidate
  event.respondWith(staleWhileRevalidate(event.request, STATIC_CACHE))
})

async function cacheFirst(request, cacheName) {
  const cached = await caches.match(request)
  if (cached) return cached
  
  try {
    const response = await fetch(request)
    if (response.ok) {
      const cache = await caches.open(cacheName)
      cache.put(request, response.clone())
    }
    return response
  } catch {
    return new Response('Offline', { status: 503 })
  }
}

async function networkFirst(request, cacheName) {
  try {
    const response = await fetch(request)
    if (response.ok) {
      const cache = await caches.open(cacheName)
      cache.put(request, response.clone())
    }
    return response
  } catch {
    return caches.match(request) || new Response('Offline', { status: 503 })
  }
}

async function staleWhileRevalidate(request, cacheName) {
  const cache = await caches.open(cacheName)
  const cached = await cache.match(request)
  
  const fetchPromise = fetch(request).then(response =&gt; {
    if (response.ok) {
      cache.put(request, response.clone())
    }
    return response
  }).catch(() =&gt; cached)
  
  return cached || fetchPromise
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/pwa-offline-games">PWA for offline games</a></li>
<li><a href="/tutorials/streaming-asset-loading">Streaming asset loading</a></li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/web-audio-api-games">Web Audio API for games</a> — caching audio assets for offline play</li>
<li><a href="/tutorials/indexeddb-game-saves">IndexedDB game saves</a> — persisting game state alongside cached assets</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">MDN: Service Worker API</a> — full API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Cache">MDN: Cache API</a> — Cache interface reference</li>
<li><a href="https://web.dev/learn/pwa/service-workers/">web.dev: Service workers</a> — caching strategies and patterns</li>
<li><a href="https://developer.chrome.com/docs/workbox/">Workbox</a> — Google's library for service worker tooling</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ship a web game that loads fast (a practical checklist)]]></title>
            <link>https://app.cinevva.com/tutorials/ship-web-game-fast</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/ship-web-game-fast</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[A pragmatic, step-by-step checklist to make web games load quickly: budgets, compression, caching, asset formats, and performance measurements.]]></description>
            <content:encoded><![CDATA[<h1>Ship a web game that loads fast (a practical checklist)</h1>
<p>If players can’t <strong>start playing in seconds</strong>, they bounce. This tutorial is a practical checklist you can apply to almost any web game stack (Canvas/WebGL/WebGPU, Pixi/Three/PlayCanvas, custom engine, etc.).</p>
<h2>1) Set budgets first (or you can’t optimize)</h2>
<p>Pick budgets that match your target device. A solid default for an “instant play” experience:</p>
<ul>
<li><strong>JS+CSS shipped</strong>: under ~300–500 KB gzip (smaller is better)</li>
<li><strong>Critical assets before first input</strong>: under ~2–5 MB compressed</li>
<li><strong>Time to first input</strong>: under ~3–5 seconds on mid mobile</li>
</ul>
<p>Write these down and treat them like API contracts.</p>
<h2>2) Measure the right things</h2>
<p>In Chrome DevTools:</p>
<ul>
<li>Use <strong>Performance</strong> to capture a session and inspect long tasks.</li>
<li>Use <strong>Network</strong> to check:
<ul>
<li>transfer size vs. decoded size</li>
<li>caching headers</li>
<li>whether assets stream progressively or arrive as one giant blob</li>
</ul>
</li>
</ul>
<p>In game terms, track:</p>
<ul>
<li>“<strong>Can the player move</strong>?” time</li>
<li>“<strong>First meaningful frame</strong>” time</li>
<li>“<strong>First input latency</strong>” (input → frame)</li>
</ul>
<p>Your “first input latency” instinct now maps to a standard metric: <strong>Interaction to Next Paint (INP)</strong> replaced First Input Delay as a Core Web Vital in March 2024, and it measures the full input-to-next-paint time across all interactions, not just the first. Aim for INP under 200 ms at the 75th percentile, which is a useful external benchmark for the responsiveness numbers you already track.</p>
<h2>3) Compress everything you can</h2>
<p>Make sure your hosting serves:</p>
<ul>
<li><strong>Brotli</strong> (<code>br</code>) for text assets (JS/CSS/HTML/WASM) when available</li>
<li><strong>gzip</strong> as fallback</li>
</ul>
<p>If your host and CDN support it, <strong>Zstandard</strong> (<code>zstd</code>) is now a third option for <code>Content-Encoding</code>. It ships in Chrome and Edge 123+, Firefox 126+, and Safari 26.3+ (about 80% of users), and it can hit Brotli-class ratios at lower server CPU cost, which helps for large WASM and JSON payloads. Browsers only advertise <code>Accept-Encoding: zstd</code> over HTTPS, so keep Brotli and gzip configured as fallbacks for everyone else.</p>
<p>For WebAssembly builds, compression is often the difference between “instant” and “never loads.”</p>
<h2>4) Don’t download the whole world upfront</h2>
<p>Split your game into:</p>
<ul>
<li><strong>Boot</strong>: minimal loader + input + first scene</li>
<li><strong>Core</strong>: main gameplay systems</li>
<li><strong>Optional</strong>: extra levels, cosmetics, high-res textures, bonus audio, etc.</li>
</ul>
<p>Load “Optional” only after:</p>
<ul>
<li>the player can already play, and/or</li>
<li>you know they want that content (e.g. they reached a menu/level)</li>
</ul>
<h2>5) Choose the right asset formats</h2>
<p>For most web games:</p>
<ul>
<li><strong>Images</strong>: prefer <strong>WebP</strong> (or <strong>AVIF</strong> if you can tolerate slower encode) for UI/backgrounds.</li>
<li><strong>Audio</strong>: prefer <strong>Ogg Vorbis</strong> for general use; test <strong>AAC</strong> for Apple ecosystems.</li>
<li><strong>Video</strong>: prefer <strong>MP4/H.264</strong> for compatibility, <strong>WebM</strong> when supported and smaller.</li>
</ul>
<p>Keep an eye on decode cost: “smaller download” can still be “slower to decode.”</p>
<h2>6) Keep your first scene small and deterministic</h2>
<p>Avoid these in your first interactive scene:</p>
<ul>
<li>shader compilation storms</li>
<li>huge texture uploads</li>
<li>procedural generation that blocks the main thread</li>
<li>synchronous JSON parsing of megabyte blobs</li>
</ul>
<p>For textures specifically, ship <strong>KTX2 with Basis Universal</strong> supercompression instead of PNG or JPEG. It stays GPU-compressed after upload (transcoding to BC7 on desktop or ASTC on mobile at load), which cuts VRAM 4x to 8x and makes uploads far cheaper than decoding a full-size PNG and pushing raw pixels to the GPU.</p>
<p>If you must do heavy work, do it:</p>
<ul>
<li>incrementally across frames, or</li>
<li>in a Worker (when possible)</li>
</ul>
<h2>7) Cache aggressively (but correctly)</h2>
<p>Use long-lived caching for content-addressed assets:</p>
<ul>
<li><code>Cache-Control: public, max-age=31536000, immutable</code></li>
</ul>
<p>For HTML entrypoints, keep caching short so you can deploy updates safely.</p>
<h2>8) Make “failure” fast and readable</h2>
<p>If something goes wrong, show:</p>
<ul>
<li>a clear error message</li>
<li>a retry button</li>
<li>a link to report the issue</li>
</ul>
<p>Silent failures kill trust.</p>
<h2>9) If you use Wasm threads, understand COOP/COEP</h2>
<p>If your build depends on <code>SharedArrayBuffer</code> (common for some Wasm threading setups), you’ll likely need <strong>cross-origin isolation</strong> headers:</p>
<ul>
<li><code>Cross-Origin-Opener-Policy: same-origin</code></li>
<li><code>Cross-Origin-Embedder-Policy: require-corp</code></li>
</ul>
<p>You have two choices for the COEP header. <code>require-corp</code> is the strict option but means every cross-origin asset (CDN textures, third-party scripts) must send a <code>Cross-Origin-Resource-Policy</code> header or it gets blocked. <code>Cross-Origin-Embedder-Policy: credentialless</code> also unlocks <code>SharedArrayBuffer</code> and cross-origin isolation, but loads cross-origin resources without credentials instead of requiring them to opt in with CORP. If you pull assets from a CDN you don’t control, <code>credentialless</code> is usually the less painful path.</p>
<p>Test early on your real host, because headers and third‑party embeds can break things.</p>
<h2>10) Make it playable without an SDK</h2>
<p>If you’re targeting Cinevva’s creator workflow, aim for:</p>
<ul>
<li>one URL that boots reliably</li>
<li>no required logins to start a demo</li>
<li>predictable input controls</li>
</ul>
<p>Then you’re ready for distribution without integrating extra SDKs.</p>
<p>Related:</p>
<ul>
<li><a href="/creators">For game creators</a></li>
<li><a href="/ai-content">AI-generated content policy</a></li>
<li><a href="/tutorials/streaming-asset-loading">Streaming asset loading</a> — progressive loading patterns for large games</li>
<li><a href="/tutorials/service-workers-caching">Service workers for game caching</a> — cache assets for instant repeat visits</li>
<li><a href="/guides/web-game-engines-comparison">Web Game Engines Comparison</a> — build sizes and load times across engines</li>
<li><a href="/guides/itch-io-launch-guide">How to Launch Your Game on itch.io</a> — optimizing browser games for <a href="http://itch.io">itch.io</a> embeds</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming asset loading for web games]]></title>
            <link>https://app.cinevva.com/tutorials/streaming-asset-loading</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/streaming-asset-loading</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Load game assets progressively: prioritization, streaming, caching, and showing progress. Keep players engaged while loading.]]></description>
            <content:encoded><![CDATA[<h1>Streaming asset loading for web games</h1>
<p>Players won't wait for a 100MB download. Load assets progressively so they can play while the rest loads in the background.</p>
<h2>1) The loading strategy</h2>
<p>Split assets into tiers:</p>
<ol>
<li><strong>Critical</strong> — Required to show first screen (&lt; 1MB)</li>
<li><strong>Gameplay</strong> — Required to play (&lt; 10MB)</li>
<li><strong>Enhancement</strong> — Nice to have (load in background)</li>
</ol>
<h2>2) Basic asset loader</h2>
<pre><code class="language-js">class AssetLoader {
  constructor() {
    this.cache = new Map()
    this.loading = new Map()
  }
  
  async loadImage(url) {
    if (this.cache.has(url)) return this.cache.get(url)
    if (this.loading.has(url)) return this.loading.get(url)
    
    const promise = new Promise((resolve, reject) =&gt; {
      const img = new Image()
      img.onload = () =&gt; {
        this.cache.set(url, img)
        this.loading.delete(url)
        resolve(img)
      }
      img.onerror = reject
      img.src = url
    })
    
    this.loading.set(url, promise)
    return promise
  }
  
  async loadJSON(url) {
    if (this.cache.has(url)) return this.cache.get(url)
    
    const response = await fetch(url)
    const data = await response.json()
    this.cache.set(url, data)
    return data
  }
  
  async loadAudio(url, audioCtx) {
    if (this.cache.has(url)) return this.cache.get(url)
    
    const response = await fetch(url)
    const buffer = await response.arrayBuffer()
    const audioBuffer = await audioCtx.decodeAudioData(buffer)
    this.cache.set(url, audioBuffer)
    return audioBuffer
  }
}
</code></pre>
<h2>3) Loading with progress</h2>
<pre><code class="language-js">async function loadWithProgress(url, onProgress) {
  const response = await fetch(url)
  const contentLength = response.headers.get('Content-Length')
  const total = parseInt(contentLength, 10)
  
  const reader = response.body.getReader()
  const chunks = []
  let received = 0
  
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    
    chunks.push(value)
    received += value.length
    onProgress(received / total)
  }
  
  const blob = new Blob(chunks)
  return blob
}
</code></pre>
<p>Heads up: when the server compresses the response (gzip or brotli, which most CDNs do by default), <code>Content-Length</code> is the compressed size while the chunks you read are already decompressed. That makes <code>received / total</code> overshoot 100%. For an accurate byte-level progress bar on compressed responses, either serve the asset uncompressed, send your own uncompressed-size header, or fall back to <code>XMLHttpRequest</code>'s <code>onprogress</code> event, which reports real transfer progress.</p>
<h2>4) Batch loading with overall progress</h2>
<pre><code class="language-js">async function loadAssets(manifest, onProgress) {
  const total = manifest.length
  let completed = 0
  const results = {}
  
  const promises = manifest.map(async (item) =&gt; {
    const asset = await loadAsset(item.url, item.type)
    results[item.name] = asset
    completed++
    onProgress(completed / total, item.name)
  })
  
  await Promise.all(promises)
  return results
}

// Usage
const manifest = [
  { name: 'player', url: 'player.png', type: 'image' },
  { name: 'level1', url: 'level1.json', type: 'json' },
  { name: 'music', url: 'music.mp3', type: 'audio' },
]

const assets = await loadAssets(manifest, (progress, name) =&gt; {
  console.log(`Loading: ${Math.round(progress * 100)}% (${name})`)
})
</code></pre>
<h2>5) Priority queue loader</h2>
<pre><code class="language-js">class PriorityLoader {
  constructor(concurrency = 4) {
    this.queue = []
    this.active = 0
    this.concurrency = concurrency
  }
  
  add(url, priority = 0) {
    return new Promise((resolve, reject) =&gt; {
      this.queue.push({ url, priority, resolve, reject })
      this.queue.sort((a, b) =&gt; b.priority - a.priority)
      this.process()
    })
  }
  
  async process() {
    if (this.active &gt;= this.concurrency || this.queue.length === 0) return
    
    this.active++
    const { url, resolve, reject } = this.queue.shift()
    
    try {
      const response = await fetch(url)
      const blob = await response.blob()
      resolve(blob)
    } catch (err) {
      reject(err)
    }
    
    this.active--
    this.process()
  }
}

// Usage
const loader = new PriorityLoader()
loader.add('critical.png', 10)  // Load first
loader.add('optional.png', 1)   // Load later
</code></pre>
<h2>6) Lazy loading for levels</h2>
<pre><code class="language-js">class LevelManager {
  constructor(loader) {
    this.loader = loader
    this.levels = new Map()
  }
  
  async preload(levelId) {
    if (this.levels.has(levelId)) return
    
    const manifest = await this.loader.loadJSON(`levels/${levelId}/manifest.json`)
    const assets = await this.loadLevelAssets(manifest)
    this.levels.set(levelId, { manifest, assets })
  }
  
  async loadLevelAssets(manifest) {
    // Load only what's needed for this level
    const assets = {}
    
    for (const texture of manifest.textures) {
      assets[texture.name] = await this.loader.loadImage(texture.url)
    }
    
    return assets
  }
  
  unload(levelId) {
    this.levels.delete(levelId)
    // Assets can be garbage collected
  }
}
</code></pre>
<h2>7) Streaming large files</h2>
<p>For large files (3D models, audio), stream and process incrementally:</p>
<pre><code class="language-js">async function streamLargeFile(url, onChunk) {
  const response = await fetch(url)
  const reader = response.body.getReader()
  
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    onChunk(value)
  }
}

// For audio: use Media Source Extensions
// For 3D: process mesh data as it arrives
</code></pre>
<h2>8) Caching loaded assets</h2>
<p>Combine with IndexedDB for persistent caching:</p>
<pre><code class="language-js">class CachedLoader {
  constructor() {
    this.memCache = new Map()
    this.dbName = 'AssetCache'
  }
  
  async loadImage(url) {
    // Check memory
    if (this.memCache.has(url)) return this.memCache.get(url)
    
    // Check IndexedDB
    const cached = await this.getFromDB(url)
    if (cached) {
      const img = await this.blobToImage(cached)
      this.memCache.set(url, img)
      return img
    }
    
    // Fetch and cache
    const response = await fetch(url)
    const blob = await response.blob()
    await this.saveToDB(url, blob)
    
    const img = await this.blobToImage(blob)
    this.memCache.set(url, img)
    return img
  }
  
  blobToImage(blob) {
    return new Promise((resolve) =&gt; {
      const img = new Image()
      img.onload = () =&gt; {
        URL.revokeObjectURL(img.src)
        resolve(img)
      }
      img.src = URL.createObjectURL(blob)
    })
  }
  
  // IndexedDB methods...
}
</code></pre>
<h2>9) Loading screen pattern</h2>
<pre><code class="language-js">class LoadingScreen {
  constructor(canvas) {
    this.canvas = canvas
    this.ctx = canvas.getContext('2d')
    this.progress = 0
    this.message = 'Loading...'
  }
  
  update(progress, message) {
    this.progress = progress
    this.message = message || this.message
    this.render()
  }
  
  render() {
    const { ctx, canvas } = this
    ctx.fillStyle = '#1a1a2e'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // Progress bar
    const barWidth = canvas.width * 0.6
    const barHeight = 20
    const x = (canvas.width - barWidth) / 2
    const y = canvas.height / 2
    
    ctx.fillStyle = '#333'
    ctx.fillRect(x, y, barWidth, barHeight)
    
    ctx.fillStyle = '#4ade80'
    ctx.fillRect(x, y, barWidth * this.progress, barHeight)
    
    // Text
    ctx.fillStyle = '#fff'
    ctx.font = '16px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText(this.message, canvas.width / 2, y - 20)
    ctx.fillText(`${Math.round(this.progress * 100)}%`, canvas.width / 2, y + 50)
  }
}
</code></pre>
<h2>10) Best practices</h2>
<ul>
<li><strong>Show something immediately</strong> — even a static image</li>
<li><strong>Load what's visible first</strong> — textures for the current view</li>
<li><strong>Use placeholders</strong> — low-res images that upgrade</li>
<li><strong>Prefetch next level</strong> — while player is still playing</li>
<li><strong>Handle failures gracefully</strong> — retry logic, fallbacks</li>
</ul>
<pre><code class="language-js">async function loadWithRetry(url, maxRetries = 3) {
  for (let i = 0; i &lt; maxRetries; i++) {
    try {
      return await fetch(url)
    } catch (err) {
      if (i === maxRetries - 1) throw err
      await new Promise(r =&gt; setTimeout(r, 1000 * (i + 1)))
    }
  }
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/service-workers-caching">Service workers for game caching</a></li>
<li><a href="/tutorials/indexeddb-game-saves">IndexedDB game saves</a></li>
<li><a href="/tutorials/web-workers-game-logic">Web Workers for game logic</a> — decode and process assets off the main thread</li>
<li><a href="/guides/game-assets-guide">Where to Find Free Game Assets</a> — sources for 3D models, textures, and audio to stream</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">MDN: Fetch API</a> — streaming responses and ReadableStream</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream">MDN: ReadableStream</a> — processing streamed data chunks</li>
<li><a href="https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html">glTF 2.0 specification</a> — the standard format for streaming 3D assets</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text rendering in web games]]></title>
            <link>https://app.cinevva.com/tutorials/text-rendering-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/text-rendering-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Render text in games: Canvas text, bitmap fonts, SDF fonts, and performance. From simple labels to dialogue systems.]]></description>
            <content:encoded><![CDATA[<h1>Text rendering in web games</h1>
<p>Text is everywhere in games—scores, dialogue, menus, damage numbers. This tutorial covers different approaches and when to use each.</p>
<h2>1) Canvas text basics</h2>
<p>The simplest approach:</p>
<pre><code class="language-js">ctx.font = '24px Arial'
ctx.fillStyle = '#ffffff'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText('Score: 1000', canvas.width / 2, 50)
</code></pre>
<p>If you need tighter or looser spacing for headings and HUD labels, the canvas context now supports <code>letterSpacing</code> and <code>wordSpacing</code> directly. Both take CSS length strings and reached cross-browser Baseline in 2025, so you no longer have to draw glyphs one at a time to fake kerning:</p>
<pre><code class="language-js">ctx.font = '24px sans-serif'
ctx.letterSpacing = '2px'
ctx.wordSpacing = '6px'
ctx.fillText('GAME OVER', 100, 100)
</code></pre>
<p>Reset them to <code>'0px'</code> when you're done, since they persist on the context like <code>font</code> and <code>fillStyle</code>.</p>
<h2>2) Text with outline</h2>
<pre><code class="language-js">function drawTextWithOutline(ctx, text, x, y, fillColor, outlineColor, outlineWidth = 2) {
  ctx.font = '24px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  
  ctx.strokeStyle = outlineColor
  ctx.lineWidth = outlineWidth
  ctx.strokeText(text, x, y)
  
  ctx.fillStyle = fillColor
  ctx.fillText(text, x, y)
}

drawTextWithOutline(ctx, 'GAME OVER', 400, 300, '#fff', '#000', 3)
</code></pre>
<h2>3) Text with shadow</h2>
<pre><code class="language-js">function drawTextWithShadow(ctx, text, x, y, color, shadowOffset = 2) {
  ctx.font = '32px sans-serif'
  ctx.textAlign = 'left'
  ctx.textBaseline = 'top'
  
  // Shadow
  ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
  ctx.fillText(text, x + shadowOffset, y + shadowOffset)
  
  // Main text
  ctx.fillStyle = color
  ctx.fillText(text, x, y)
}
</code></pre>
<h2>4) Bitmap font rendering</h2>
<p>For pixel art games or consistent cross-platform look:</p>
<pre><code class="language-js">class BitmapFont {
  constructor(image, charWidth, charHeight, chars) {
    this.image = image
    this.charWidth = charWidth
    this.charHeight = charHeight
    this.chars = chars
  }
  
  draw(ctx, text, x, y, scale = 1) {
    const w = this.charWidth * scale
    const h = this.charHeight * scale
    
    for (let i = 0; i &lt; text.length; i++) {
      const charIndex = this.chars.indexOf(text[i].toUpperCase())
      if (charIndex === -1) continue
      
      const sx = (charIndex % 16) * this.charWidth
      const sy = Math.floor(charIndex / 16) * this.charHeight
      
      ctx.drawImage(
        this.image,
        sx, sy, this.charWidth, this.charHeight,
        Math.round(x + i * w), Math.round(y), w, h
      )
    }
  }
  
  measureText(text, scale = 1) {
    return text.length * this.charWidth * scale
  }
}

// Usage
const font = new BitmapFont(fontImage, 8, 8, 
  'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+:; '
)
font.draw(ctx, 'SCORE: 1000', 10, 10, 2)
</code></pre>
<h2>5) Pre-rendered text for performance</h2>
<p>For static text, render once and reuse:</p>
<pre><code class="language-js">function createTextImage(text, font, color) {
  const tempCanvas = document.createElement('canvas')
  const tempCtx = tempCanvas.getContext('2d')
  
  tempCtx.font = font
  const metrics = tempCtx.measureText(text)
  
  tempCanvas.width = Math.ceil(metrics.width)
  tempCanvas.height = parseInt(font) * 1.5
  
  tempCtx.font = font
  tempCtx.fillStyle = color
  tempCtx.textBaseline = 'top'
  tempCtx.fillText(text, 0, 0)
  
  return tempCanvas
}

// Create once
const titleImage = createTextImage('MY GAME', '48px Impact', '#fff')

// Draw many times (fast)
ctx.drawImage(titleImage, x, y)
</code></pre>
<h2>6) Typewriter effect</h2>
<pre><code class="language-js">class TypewriterText {
  constructor(text, x, y, charsPerSecond = 20) {
    this.fullText = text
    this.x = x
    this.y = y
    this.speed = 1 / charsPerSecond
    this.timer = 0
    this.charIndex = 0
  }
  
  update(dt) {
    this.timer += dt
    while (this.timer &gt;= this.speed &amp;&amp; this.charIndex &lt; this.fullText.length) {
      this.charIndex++
      this.timer -= this.speed
    }
  }
  
  draw(ctx) {
    ctx.font = '18px monospace'
    ctx.fillStyle = '#fff'
    ctx.fillText(this.fullText.slice(0, this.charIndex), this.x, this.y)
  }
  
  isComplete() {
    return this.charIndex &gt;= this.fullText.length
  }
  
  skip() {
    this.charIndex = this.fullText.length
  }
}
</code></pre>
<h2>7) Word-wrapped text</h2>
<pre><code class="language-js">function wrapText(ctx, text, maxWidth) {
  const words = text.split(' ')
  const lines = []
  let currentLine = ''
  
  for (const word of words) {
    const testLine = currentLine ? currentLine + ' ' + word : word
    const metrics = ctx.measureText(testLine)
    
    if (metrics.width &gt; maxWidth &amp;&amp; currentLine) {
      lines.push(currentLine)
      currentLine = word
    } else {
      currentLine = testLine
    }
  }
  
  if (currentLine) lines.push(currentLine)
  return lines
}

function drawWrappedText(ctx, text, x, y, maxWidth, lineHeight) {
  const lines = wrapText(ctx, text, maxWidth)
  for (let i = 0; i &lt; lines.length; i++) {
    ctx.fillText(lines[i], x, y + i * lineHeight)
  }
}
</code></pre>
<h2>8) Dialogue box system</h2>
<pre><code class="language-js">class DialogueBox {
  constructor(x, y, width, height) {
    this.x = x
    this.y = y
    this.width = width
    this.height = height
    this.padding = 16
    this.lineHeight = 24
    this.text = ''
    this.displayedChars = 0
    this.charsPerSecond = 30
    this.timer = 0
  }
  
  show(text) {
    this.text = text
    this.displayedChars = 0
    this.timer = 0
  }
  
  update(dt) {
    if (this.displayedChars &lt; this.text.length) {
      this.timer += dt
      const charsToAdd = Math.floor(this.timer * this.charsPerSecond)
      this.displayedChars = Math.min(this.displayedChars + charsToAdd, this.text.length)
      this.timer = this.timer % (1 / this.charsPerSecond)
    }
  }
  
  skip() {
    this.displayedChars = this.text.length
  }
  
  isComplete() {
    return this.displayedChars &gt;= this.text.length
  }
  
  draw(ctx) {
    // Box background
    ctx.fillStyle = 'rgba(0, 0, 0, 0.8)'
    ctx.fillRect(this.x, this.y, this.width, this.height)
    
    // Border
    ctx.strokeStyle = '#fff'
    ctx.lineWidth = 2
    ctx.strokeRect(this.x, this.y, this.width, this.height)
    
    // Text
    ctx.font = '18px sans-serif'
    ctx.fillStyle = '#fff'
    ctx.textBaseline = 'top'
    
    const displayText = this.text.slice(0, this.displayedChars)
    const maxWidth = this.width - this.padding * 2
    const lines = wrapText(ctx, displayText, maxWidth)
    
    for (let i = 0; i &lt; lines.length; i++) {
      ctx.fillText(
        lines[i],
        this.x + this.padding,
        this.y + this.padding + i * this.lineHeight
      )
    }
    
    // Continue indicator
    if (this.isComplete()) {
      ctx.fillText('▼', this.x + this.width - 24, this.y + this.height - 24)
    }
  }
}
</code></pre>
<h2>9) Floating damage numbers</h2>
<pre><code class="language-js">class FloatingText {
  constructor(text, x, y, color = '#fff') {
    this.text = text
    this.x = x
    this.y = y
    this.color = color
    this.vy = -60
    this.lifetime = 1
    this.age = 0
  }
  
  update(dt) {
    this.y += this.vy * dt
    this.vy *= 0.95
    this.age += dt
  }
  
  draw(ctx) {
    const alpha = 1 - (this.age / this.lifetime)
    ctx.font = 'bold 20px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillStyle = this.color
    ctx.globalAlpha = alpha
    ctx.fillText(this.text, Math.round(this.x), Math.round(this.y))
    ctx.globalAlpha = 1
  }
  
  isExpired() {
    return this.age &gt;= this.lifetime
  }
}

// Manager
const floatingTexts = []

function spawnDamageNumber(damage, x, y) {
  const color = damage &gt; 50 ? '#ff4444' : '#ffff44'
  floatingTexts.push(new FloatingText(damage.toString(), x, y, color))
}

function updateFloatingTexts(dt) {
  for (let i = floatingTexts.length - 1; i &gt;= 0; i--) {
    floatingTexts[i].update(dt)
    if (floatingTexts[i].isExpired()) {
      floatingTexts.splice(i, 1)
    }
  }
}
</code></pre>
<h2>10) WebGL text (SDF fonts)</h2>
<p>For WebGL games, Signed Distance Field fonts scale cleanly:</p>
<pre><code class="language-js">// SDF shader fragment
const sdfFragmentShader = `
  precision mediump float;
  
  uniform sampler2D u_texture;
  uniform vec4 u_color;
  varying vec2 v_texCoord;
  
  void main() {
    float distance = texture2D(u_texture, v_texCoord).a;
    float alpha = smoothstep(0.4, 0.6, distance);
    gl_FragColor = vec4(u_color.rgb, u_color.a * alpha);
  }
`

// Libraries like msdf-bmfont-xml can generate SDF font atlases
</code></pre>
<p>For three.js scenes specifically, <code>troika-three-text</code> is a good option. Instead of pre-baking an atlas, it parses <code>.ttf</code>/<code>.otf</code>/<code>.woff</code> files and generates the SDF glyphs on the fly in a web worker, and it handles kerning, ligatures, and right-to-left scripts for you.</p>
<p>For most 2D Canvas games, bitmap fonts or pre-rendered Canvas text work well.</p>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a></li>
<li><a href="/tutorials/pixel-art-rendering">Pixel art rendering</a></li>
<li><a href="/tutorials/webgl-fundamentals-for-games">WebGL fundamentals</a></li>
<li><a href="/tutorials/responsive-game-canvas">Responsive game canvas</a> — scaling text with canvas resolution and DPI</li>
<li><a href="/guides/game-assets-guide">Where to Find Free Game Assets</a> — font and UI asset sources</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tone.js for game audio]]></title>
            <link>https://app.cinevva.com/tutorials/tone-js-game-audio</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/tone-js-game-audio</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Build satisfying game sounds with Tone.js: synth-based sound effects, dynamic music, and reactive audio that responds to gameplay.]]></description>
            <content:encoded><![CDATA[<h1>Tone.js for Game Audio</h1>
<p>Tone.js sits on top of the Web Audio API and makes synthesized audio practical. Instead of loading audio files, you generate sounds programmatically. This means zero load time, infinite variations, and sounds that can react to gameplay in real time.</p>
<p><strong>Try it (click buttons to hear synthesized game sounds):</strong></p>
<ToneDemo />
<h2>Why Tone.js Instead of Audio Files</h2>
<p>Audio files work fine for music and complex sounds. But for game sound effects, synthesis has real advantages. You can vary pitch and timing on every play so sounds don't feel repetitive. You can generate sounds on the fly based on game state. And you skip the network requests entirely.</p>
<p>The downside is that synthesized audio takes more CPU than playing a file. For simple games this isn't a problem. For complex games, you might mix both approaches.</p>
<h2>Setup</h2>
<p>Load Tone.js from a CDN or npm:</p>
<pre><code class="language-html">&lt;script src=&quot;https://unpkg.com/tone@15/build/Tone.js&quot;&gt;&lt;/script&gt;
</code></pre>
<p>Or with npm:</p>
<pre><code class="language-bash">npm install tone
</code></pre>
<pre><code class="language-js">import * as Tone from 'tone'
</code></pre>
<h2>The Autoplay Problem</h2>
<p>Browsers block audio until user interaction. Tone.js handles this, but you need to call <code>Tone.start()</code> on a user gesture:</p>
<pre><code class="language-js">document.addEventListener('click', async () =&gt; {
  await Tone.start()
  console.log('Audio ready')
}, { once: true })
</code></pre>
<p>Without this, your AudioContext stays suspended and nothing plays.</p>
<h2>Your First Synth</h2>
<p>A synth generates sound. The simplest one is <code>Tone.Synth</code>:</p>
<pre><code class="language-js">const synth = new Tone.Synth().toDestination()

// Play a note
synth.triggerAttackRelease('C4', '8n')
</code></pre>
<p><code>triggerAttackRelease</code> plays a note for a duration. <code>'C4'</code> is middle C. <code>'8n'</code> is an eighth note at the current tempo.</p>
<p>The synth has an oscillator (the sound source) and an envelope (how the sound fades in and out). You can customize both:</p>
<pre><code class="language-js">const synth = new Tone.Synth({
  oscillator: { type: 'triangle' },
  envelope: {
    attack: 0.02,
    decay: 0.2,
    sustain: 0.3,
    release: 0.4,
  },
}).toDestination()
</code></pre>
<p>Oscillator types include <code>sine</code> (pure, mellow), <code>triangle</code> (soft), <code>sawtooth</code> (buzzy), and <code>square</code> (hollow, retro).</p>
<h2>Building a Sound Effects System</h2>
<p>For a game, you want multiple synths for different sound types. Here's a pattern that works well:</p>
<pre><code class="language-js">let isInitialized = false
let softSynth = null
let subSynth = null
let noiseSynth = null
let sfxGain = null

function initSFX() {
  if (isInitialized) return
  
  // Master volume control
  sfxGain = new Tone.Gain(0.7).toDestination()
  
  // Soft synth for melodic sounds
  softSynth = new Tone.PolySynth(Tone.Synth, {
    maxPolyphony: 6,
    oscillator: { type: 'sine' },
    envelope: {
      attack: 0.02,
      decay: 0.2,
      sustain: 0.3,
      release: 0.4,
    },
    volume: -8,
  }).connect(sfxGain)
  
  // Sub bass for deep impacts
  subSynth = new Tone.Synth({
    oscillator: { type: 'sine' },
    envelope: {
      attack: 0.02,
      decay: 0.3,
      sustain: 0.1,
      release: 0.3,
    },
    volume: -8,
  }).connect(sfxGain)
  
  // Noise for texture
  noiseSynth = new Tone.NoiseSynth({
    noise: { type: 'pink' },
    envelope: {
      attack: 0.02,
      decay: 0.15,
      sustain: 0,
      release: 0.15,
    },
    volume: -20,
  }).connect(sfxGain)
  
  isInitialized = true
}
</code></pre>
<p><code>PolySynth</code> lets you play multiple notes at once. Regular <code>Synth</code> is monophonic.</p>
<h2>Game Sound Examples</h2>
<p>Here are some common game sounds and how to create them:</p>
<p><strong>Coin collect</strong> - ascending notes feel rewarding:</p>
<pre><code class="language-js">function coinCollect() {
  const now = Tone.now()
  softSynth.triggerAttackRelease('C4', '8n', now, 0.3)
  softSynth.triggerAttackRelease('E4', '8n', now + 0.1, 0.35)
  softSynth.triggerAttackRelease('G4', '4n', now + 0.2, 0.4)
}
</code></pre>
<p><strong>Jump</strong> - quick upward sweep:</p>
<pre><code class="language-js">function jump() {
  const synth = new Tone.Synth({
    oscillator: { type: 'square' },
    envelope: { attack: 0.01, decay: 0.1, sustain: 0, release: 0.1 },
  }).toDestination()
  
  const now = Tone.now()
  synth.frequency.setValueAtTime(150, now)
  synth.frequency.exponentialRampToValueAtTime(400, now + 0.1)
  synth.triggerAttackRelease('C4', '8n', now, 0.2)
}
</code></pre>
<p><strong>Hit/damage</strong> - descending with noise:</p>
<pre><code class="language-js">function hit() {
  const now = Tone.now()
  subSynth.triggerAttackRelease('E2', '4n', now, 0.5)
  noiseSynth.triggerAttackRelease('4n', now, 0.25)
}
</code></pre>
<p><strong>Death</strong> - sad descending notes:</p>
<pre><code class="language-js">function death() {
  const now = Tone.now()
  softSynth.triggerAttackRelease('E4', '4n', now, 0.4)
  softSynth.triggerAttackRelease('C4', '4n', now + 0.2, 0.35)
  softSynth.triggerAttackRelease('A3', '4n', now + 0.4, 0.3)
}
</code></pre>
<h2>Adding Effects</h2>
<p>Effects make sounds richer. Chain them between the synth and destination:</p>
<pre><code class="language-js">const filter = new Tone.Filter({
  frequency: 3000,
  type: 'lowpass',
  rolloff: -12,
})

const reverb = new Tone.Reverb({
  decay: 1.2,
  wet: 0.25,
})

const gain = new Tone.Gain(0.7)

// Chain: synth -&gt; filter -&gt; reverb -&gt; gain -&gt; destination
filter.connect(reverb)
reverb.connect(gain)
gain.toDestination()

const synth = new Tone.Synth().connect(filter)
</code></pre>
<p>Lowpass filter cuts harsh high frequencies. Reverb adds space. Gain controls volume.</p>
<h2>Rate Limiting</h2>
<p>If your game triggers many sounds rapidly, they can overlap and create a mess. Add rate limiting:</p>
<pre><code class="language-js">const MIN_INTERVAL_MS = 35
let lastNoteTime = 0

function canPlayNote() {
  const now = performance.now()
  if (now - lastNoteTime &lt; MIN_INTERVAL_MS) {
    return false
  }
  lastNoteTime = now
  return true
}

function playSound() {
  if (!canPlayNote()) return
  synth.triggerAttackRelease('C4', '8n')
}
</code></pre>
<h2>Dynamic Background Music</h2>
<p>For music that reacts to gameplay, use a beat-based system. Stems you generate with the <a href="/tools/music">game music generator</a> at a fixed BPM drop straight into it:</p>
<pre><code class="language-js">const BPM = 140
const BEAT_MS = (60 / BPM) * 1000

let bassSynth = null
let kickDrum = null
let beatInterval = null
let beatCount = 0
let energy = 0.3

const PROGRESSION = [
  { root: 'E2', chord: ['E3', 'G3', 'B3'] },
  { root: 'C2', chord: ['C3', 'E3', 'G3'] },
  { root: 'D2', chord: ['D3', 'F#3', 'A3'] },
  { root: 'A1', chord: ['A2', 'C3', 'E3'] },
]

function playBeat() {
  const beatInMeasure = beatCount % 8
  const chordIndex = Math.floor(beatCount / 8) % PROGRESSION.length
  const chord = PROGRESSION[chordIndex]
  const now = Tone.now()
  
  // Bass on beat 1
  if (beatInMeasure === 0) {
    bassSynth.triggerAttackRelease(chord.root, '4n', now, 0.6)
  }
  
  // Kick drum - only when energy is high
  if (beatInMeasure === 0 &amp;&amp; energy &gt; 0.3) {
    kickDrum.triggerAttackRelease('C1', '8n', now, 0.4)
  }
  
  beatCount++
}

function startMusic() {
  beatInterval = setInterval(playBeat, BEAT_MS)
}

function stopMusic() {
  clearInterval(beatInterval)
}

// Game events affect energy
function onEnemyKill() {
  energy = Math.min(1, energy + 0.1)
}
</code></pre>
<p>The music intensity changes based on what's happening in the game.</p>
<h2>Drums with MembraneSynth and NoiseSynth</h2>
<p>For percussion, use specialized synths:</p>
<pre><code class="language-js">// Kick drum
const kick = new Tone.MembraneSynth({
  pitchDecay: 0.05,
  octaves: 4,
  envelope: {
    attack: 0.001,
    decay: 0.2,
    sustain: 0,
    release: 0.1,
  },
  volume: -14,
}).toDestination()

kick.triggerAttackRelease('C1', '8n')

// Snare
const snare = new Tone.NoiseSynth({
  noise: { type: 'white' },
  envelope: {
    attack: 0.002,
    decay: 0.15,
    sustain: 0,
    release: 0.1,
  },
  volume: -12,
}).toDestination()

snare.triggerAttackRelease('8n')

// Hi-hat
const hihat = new Tone.NoiseSynth({
  noise: { type: 'white' },
  envelope: {
    attack: 0.001,
    decay: 0.04,
    sustain: 0,
    release: 0.03,
  },
  volume: -22,
}).toDestination()

hihat.triggerAttackRelease('32n')
</code></pre>
<h2>Cleanup</h2>
<p>Dispose of synths when you're done to free resources:</p>
<pre><code class="language-js">function cleanup() {
  if (softSynth) softSynth.dispose()
  if (subSynth) subSynth.dispose()
  if (noiseSynth) noiseSynth.dispose()
  if (sfxGain) sfxGain.dispose()
}
</code></pre>
<h2>Common Mistakes</h2>
<p><strong>Not waiting for Tone.start()</strong> - Audio won't play until the context is started on user interaction.</p>
<p><strong>Creating synths on every sound</strong> - Create synths once at init, reuse them. Creating new ones every time leaks memory.</p>
<p><strong>Too many overlapping sounds</strong> - Use rate limiting and deduplication to prevent audio mush.</p>
<p><strong>Harsh frequencies</strong> - Use lowpass filters and softer oscillator types (sine, triangle) for sounds that won't annoy players.</p>
<h2>More Resources</h2>
<p><a href="/tutorials/web-audio-api-games">Web Audio API for games</a> covers the underlying API and loading audio files.</p>
<p><a href="https://tonejs.github.io/">Tone.js documentation</a> has the full API reference.</p>
<p><a href="/guides/game-assets-guide">Where to Find Free Game Assets</a> includes audio and sound effect providers like Freesound.</p>
<p><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a> covers iOS audio restrictions and touch-to-unlock patterns.</p>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Audio API for games]]></title>
            <link>https://app.cinevva.com/tutorials/web-audio-api-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/web-audio-api-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Implement game audio with Web Audio API: sound effects, music, spatial audio, and mixing. Practical patterns that work.]]></description>
            <content:encoded><![CDATA[<h1>Web Audio API for Games</h1>
<p>Good audio transforms a game. A silent game feels lifeless. The Web Audio API gives you low-latency sound effects, music playback, and even 3D spatial audio, all in the browser.</p>
<p><strong>Try it (click a button to hear synthesized sounds):</strong></p>
<AudioDemo />
<h2>The Autoplay Problem</h2>
<p>Before anything else, you need to understand autoplay restrictions. Browsers block audio until the user interacts with your page. This is a good thing (nobody wants websites blasting sound on load), but it means you have to initialize audio in response to a click, tap, or keypress.</p>
<pre><code class="language-js">let audioCtx = null

function initAudio() {
  if (!audioCtx) {
    audioCtx = new AudioContext()
  }
  if (audioCtx.state === 'suspended') {
    audioCtx.resume()
  }
  return audioCtx
}

// Initialize on first interaction
document.addEventListener('click', () =&gt; initAudio(), { once: true })
document.addEventListener('keydown', () =&gt; initAudio(), { once: true })
</code></pre>
<p>If you try to play audio before this, it silently fails or the AudioContext stays suspended. This catches a lot of developers off guard.</p>
<h2>Loading Sounds</h2>
<p>Audio files need to be decoded before playback. Fetch the file, decode it, and keep the buffer around for reuse:</p>
<pre><code class="language-js">async function loadSound(url) {
  const response = await fetch(url)
  const arrayBuffer = await response.arrayBuffer()
  const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer)
  return audioBuffer
}
</code></pre>
<p>Decoding takes time, so load all your sounds during a loading screen, not when you need to play them.</p>
<h2>Playing Sounds</h2>
<p>To play a sound, create a buffer source, connect it through a gain node for volume control, and start it:</p>
<pre><code class="language-js">function playSound(buffer, volume = 1) {
  const source = audioCtx.createBufferSource()
  source.buffer = buffer
  
  const gainNode = audioCtx.createGain()
  gainNode.gain.value = volume
  
  source.connect(gainNode)
  gainNode.connect(audioCtx.destination)
  
  source.start(0)
  return source
}
</code></pre>
<p>Buffer sources are one-shot. Once a source finishes playing, you can't restart it. Create a new one each time you play. This feels wasteful but it's how the API works, and browsers optimize for it.</p>
<h2>A Sound Manager</h2>
<p>For a real game, wrap everything in a manager class:</p>
<pre><code class="language-js">class SoundManager {
  constructor() {
    this.ctx = null
    this.sounds = new Map()
    this.masterGain = null
  }
  
  init() {
    this.ctx = new AudioContext()
    this.masterGain = this.ctx.createGain()
    this.masterGain.connect(this.ctx.destination)
  }
  
  async load(name, url) {
    const response = await fetch(url)
    const buffer = await this.ctx.decodeAudioData(await response.arrayBuffer())
    this.sounds.set(name, buffer)
  }
  
  play(name, volume = 1) {
    const buffer = this.sounds.get(name)
    if (!buffer) return
    
    const source = this.ctx.createBufferSource()
    source.buffer = buffer
    
    const gain = this.ctx.createGain()
    gain.gain.value = volume
    
    source.connect(gain)
    gain.connect(this.masterGain)
    source.start(0)
    
    return source
  }
  
  setMasterVolume(v) {
    this.masterGain.gain.value = v
  }
}
</code></pre>
<p>The master gain node lets you implement a global volume slider. All sounds route through it.</p>
<h2>Background Music</h2>
<p>Music needs looping and the ability to stop or fade out. If you don't have a track yet, the <a href="/tools/music">game music generator</a> writes one from a description of the scene, and the player below handles the loop seam with a fade:</p>
<pre><code class="language-js">class MusicPlayer {
  constructor(ctx, masterGain) {
    this.ctx = ctx
    this.masterGain = masterGain
    this.currentTrack = null
    this.gain = ctx.createGain()
    this.gain.connect(masterGain)
  }
  
  play(buffer, volume = 0.5) {
    this.stop()
    
    this.currentTrack = this.ctx.createBufferSource()
    this.currentTrack.buffer = buffer
    this.currentTrack.loop = true
    this.currentTrack.connect(this.gain)
    this.gain.gain.value = volume
    this.currentTrack.start(0)
  }
  
  stop() {
    if (this.currentTrack) {
      this.currentTrack.stop()
      this.currentTrack = null
    }
  }
  
  fadeOut(duration = 1) {
    this.gain.gain.linearRampToValueAtTime(0, this.ctx.currentTime + duration)
  }
}
</code></pre>
<p>The <code>linearRampToValueAtTime</code> method gives you smooth fades instead of abrupt cuts.</p>
<h2>Spatial Audio</h2>
<p>For 3D games, you can position sounds in space. Sounds get quieter as they move away from the listener:</p>
<pre><code class="language-js">function playSpatialSound(buffer, x, y, z) {
  const source = audioCtx.createBufferSource()
  source.buffer = buffer
  
  const panner = audioCtx.createPanner()
  panner.panningModel = 'HRTF'
  panner.distanceModel = 'inverse'
  panner.refDistance = 1
  panner.maxDistance = 100
  panner.positionX.value = x
  panner.positionY.value = y
  panner.positionZ.value = z
  
  source.connect(panner)
  panner.connect(audioCtx.destination)
  source.start(0)
}

function updateListener(x, y, z, fx, fy, fz) {
  const listener = audioCtx.listener
  listener.positionX.value = x
  listener.positionY.value = y
  listener.positionZ.value = z
  listener.forwardX.value = fx
  listener.forwardY.value = fy
  listener.forwardZ.value = fz
  listener.upX.value = 0
  listener.upY.value = 1
  listener.upZ.value = 0
}
</code></pre>
<p>Call <code>updateListener</code> each frame with the camera or player position. The panner automatically adjusts volume and stereo panning based on distance and direction.</p>
<h2>Rapid Fire Sounds</h2>
<p>For sounds that play many times per second (gunfire, footsteps), you don't want overlapping instances to pile up. A simple pool pattern helps:</p>
<pre><code class="language-js">class SoundPool {
  constructor(ctx, buffer, size = 8) {
    this.sources = []
    this.index = 0
    this.ctx = ctx
    this.buffer = buffer
    this.size = size
  }
  
  play(volume = 1) {
    const source = this.ctx.createBufferSource()
    source.buffer = this.buffer
    
    const gain = this.ctx.createGain()
    gain.gain.value = volume
    
    source.connect(gain)
    gain.connect(this.ctx.destination)
    source.start(0)
    
    this.index = (this.index + 1) % this.size
  }
}
</code></pre>
<p>The pool limits how many instances of the same sound can play simultaneously. When you hit the limit, the oldest one gets replaced.</p>
<h2>Audio Formats</h2>
<p>Different formats work better in different situations:</p>
<p>MP3 works everywhere and is good for music. OGG Vorbis has better quality at the same file size. Safari was the long holdout, but it added native Ogg Vorbis playback in Safari 18.4, so all current major browsers support it now. You'll still want an MP3 fallback if you care about older Safari versions. AAC/M4A works well on Apple devices. WAV is uncompressed and large, but decodes instantly, which is good for short sound effects where you can afford the file size. WebM/Opus is the best quality-to-size ratio but only works in modern browsers.</p>
<p>For maximum compatibility, provide fallbacks:</p>
<pre><code class="language-js">const audioUrl = canPlayOgg() ? 'sound.ogg' : 'sound.mp3'
</code></pre>
<h2>Useful Tricks</h2>
<p><strong>Pitch variation</strong> makes repeated sounds feel less robotic:</p>
<pre><code class="language-js">function playWithPitchVariation(buffer, variance = 0.1) {
  const source = audioCtx.createBufferSource()
  source.buffer = buffer
  source.playbackRate.value = 1 + (Math.random() - 0.5) * variance
  source.connect(audioCtx.destination)
  source.start(0)
}
</code></pre>
<p>Each gunshot or footstep sounds slightly different.</p>
<p><strong>Ducking</strong> lowers music volume during dialogue or important sounds:</p>
<pre><code class="language-js">function duckMusic(musicGain, duration = 0.3) {
  musicGain.gain.linearRampToValueAtTime(0.2, audioCtx.currentTime + duration)
}

function unduckMusic(musicGain, duration = 0.3) {
  musicGain.gain.linearRampToValueAtTime(1, audioCtx.currentTime + duration)
}
</code></pre>
<h2>iOS Gotchas</h2>
<p>iOS has stricter audio restrictions than other platforms. The AudioContext must be created and resumed during a user gesture. Some iOS versions also require you to play a sound (even a silent one) during the gesture, not just create the context. If audio works on desktop but not iOS, this is probably why.</p>
<h2>More Resources</h2>
<p><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a> covers asset compression including audio.</p>
<p><a href="/tutorials/mobile-friendly-web-games">Mobile-friendly web games</a> has more on iOS-specific issues.</p>
<p><a href="/tutorials/pwa-offline-games">PWA for offline games</a> shows how to cache audio files for offline play.</p>
<p><a href="/tutorials/tone-js-game-audio">Tone.js for game audio</a> covers procedural sound generation and music systems using a higher-level library.</p>
<p><a href="/guides/game-assets-guide">Where to Find Free Game Assets</a> lists free sound effect and music sources like Freesound and Poly Haven.</p>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API">MDN: Web Audio API</a> — full API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/AudioContext">MDN: AudioContext</a> — creating and managing audio contexts</li>
<li><a href="https://www.w3.org/TR/webaudio/">Web Audio API spec</a> — W3C specification</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Workers for game logic]]></title>
            <link>https://app.cinevva.com/tutorials/web-workers-game-logic</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/web-workers-game-logic</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Offload heavy computation to Web Workers: physics, pathfinding, AI, and procedural generation without blocking the main thread.]]></description>
            <content:encoded><![CDATA[<h1>Web Workers for game logic</h1>
<p>Web Workers let you run JavaScript in a background thread. For games, this means physics, AI, and procedural generation can run without dropping frames.</p>
<h2>1) When to use Workers</h2>
<p>Good candidates:</p>
<ul>
<li>Physics simulation</li>
<li>Pathfinding (A*, navmesh)</li>
<li>AI decision making</li>
<li>Procedural generation</li>
<li>Asset processing (image manipulation, compression)</li>
<li>Complex math (FFT, collision detection)</li>
</ul>
<p>Not ideal for:</p>
<ul>
<li>Rendering (Workers can't access DOM/Canvas directly)</li>
<li>Very small tasks (thread overhead isn't worth it)</li>
</ul>
<h2>2) Creating a basic Worker</h2>
<p><strong>worker.js:</strong></p>
<pre><code class="language-js">self.onmessage = (e) =&gt; {
  const { type, data } = e.data
  
  if (type === 'calculate') {
    const result = heavyCalculation(data)
    self.postMessage({ type: 'result', data: result })
  }
}

function heavyCalculation(input) {
  // Expensive work here
  return input * 2
}
</code></pre>
<p><strong>main.js:</strong></p>
<pre><code class="language-js">const worker = new Worker('worker.js')

worker.onmessage = (e) =&gt; {
  const { type, data } = e.data
  if (type === 'result') {
    console.log('Got result:', data)
  }
}

worker.postMessage({ type: 'calculate', data: 42 })
</code></pre>
<h2>3) Inline Workers (no separate file)</h2>
<pre><code class="language-js">function createInlineWorker(fn) {
  const blob = new Blob([`(${fn.toString()})()`], { type: 'text/javascript' })
  return new Worker(URL.createObjectURL(blob))
}

const worker = createInlineWorker(() =&gt; {
  self.onmessage = (e) =&gt; {
    const result = e.data * 2
    self.postMessage(result)
  }
})
</code></pre>
<h2>4) ES module Workers</h2>
<p>You can write worker code as an ES module and use <code>import</code> inside it, instead of <code>importScripts</code>. Pass <code>{ type: 'module' }</code> to the constructor:</p>
<pre><code class="language-js">const worker = new Worker('physics-worker.js', { type: 'module' })
</code></pre>
<p>Inside the worker you can then <code>import</code> shared math, collision, or AI helpers the same way you do on the main thread, so game logic isn't duplicated. Module workers are supported in Chrome and Edge 80+, Safari 15+, and Firefox 114+.</p>
<h2>5) Physics Worker example</h2>
<p><strong>physics-worker.js:</strong></p>
<pre><code class="language-js">const bodies = []
const FIXED_DT = 1 / 60

self.onmessage = (e) =&gt; {
  const { type, data } = e.data
  
  switch (type) {
    case 'init':
      initWorld(data)
      break
    case 'step':
      step()
      break
    case 'addBody':
      bodies.push(data)
      break
  }
}

function initWorld(config) {
  // Initialize physics world
}

function step() {
  // Update physics
  for (const body of bodies) {
    body.vy += 9.8 * FIXED_DT // Gravity
    body.x += body.vx * FIXED_DT
    body.y += body.vy * FIXED_DT
  }
  
  // Send positions back
  self.postMessage({
    type: 'positions',
    data: bodies.map(b =&gt; ({ id: b.id, x: b.x, y: b.y, rotation: b.rotation }))
  })
}
</code></pre>
<h2>6) Transferable objects for performance</h2>
<p>Large data can be transferred without copying:</p>
<pre><code class="language-js">// Main thread
const positions = new Float32Array(1000)
worker.postMessage(positions, [positions.buffer])
// positions is now unusable here (transferred)

// Worker
self.onmessage = (e) =&gt; {
  const positions = e.data
  // Work with positions
  self.postMessage(positions, [positions.buffer])
}
</code></pre>
<h2>7) Pathfinding Worker</h2>
<p><strong>pathfinding-worker.js:</strong></p>
<pre><code class="language-js">let grid = null

self.onmessage = (e) =&gt; {
  const { type, data } = e.data
  
  if (type === 'setGrid') {
    grid = data
  }
  
  if (type === 'findPath') {
    const path = aStar(data.start, data.end, grid)
    self.postMessage({ type: 'path', id: data.id, path })
  }
}

function aStar(start, end, grid) {
  // A* implementation
  const openSet = [start]
  const cameFrom = new Map()
  const gScore = new Map()
  gScore.set(key(start), 0)
  
  while (openSet.length &gt; 0) {
    // ... A* logic
  }
  
  return reconstructPath(cameFrom, end)
}

function key(pos) {
  return `${pos.x},${pos.y}`
}
</code></pre>
<h2>8) Worker pool for parallel tasks</h2>
<pre><code class="language-js">class WorkerPool {
  constructor(workerUrl, size = navigator.hardwareConcurrency || 4) {
    this.workers = []
    this.queue = []
    this.available = []
    
    for (let i = 0; i &lt; size; i++) {
      const worker = new Worker(workerUrl)
      worker.onmessage = (e) =&gt; this.handleResult(worker, e)
      this.workers.push(worker)
      this.available.push(worker)
    }
  }
  
  run(data) {
    return new Promise((resolve) =&gt; {
      const task = { data, resolve }
      
      if (this.available.length &gt; 0) {
        this.dispatch(this.available.pop(), task)
      } else {
        this.queue.push(task)
      }
    })
  }
  
  dispatch(worker, task) {
    worker._currentTask = task
    worker.postMessage(task.data)
  }
  
  handleResult(worker, e) {
    const task = worker._currentTask
    task.resolve(e.data)
    
    if (this.queue.length &gt; 0) {
      this.dispatch(worker, this.queue.shift())
    } else {
      this.available.push(worker)
    }
  }
  
  terminate() {
    this.workers.forEach(w =&gt; w.terminate())
  }
}
</code></pre>
<h2>9) SharedArrayBuffer for real-time sync</h2>
<p>With cross-origin isolation enabled, you can share memory:</p>
<pre><code class="language-js">// Main thread
const shared = new SharedArrayBuffer(1024)
const positions = new Float32Array(shared)

worker.postMessage({ type: 'init', buffer: shared })

// Worker reads/writes directly to shared memory
// No postMessage overhead for position updates
</code></pre>
<h2>10) OffscreenCanvas for Workers</h2>
<p>Render in a Worker. OffscreenCanvas is now Baseline Widely available across Chrome, Edge, Firefox, and Safari (Safari added support in 17.0 on macOS and iOS):</p>
<pre><code class="language-js">// Main thread
const canvas = document.getElementById('game')
const offscreen = canvas.transferControlToOffscreen()
worker.postMessage({ canvas: offscreen }, [offscreen])

// Worker
self.onmessage = (e) =&gt; {
  const canvas = e.data.canvas
  const ctx = canvas.getContext('2d')
  
  function render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    // Draw...
    requestAnimationFrame(render)
  }
  render()
}
</code></pre>
<h2>11) Error handling</h2>
<pre><code class="language-js">worker.onerror = (e) =&gt; {
  console.error('Worker error:', e.message, e.filename, e.lineno)
}

// In worker
self.onerror = (e) =&gt; {
  self.postMessage({ type: 'error', message: e.message })
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/coop-coep-sharedarraybuffer">Enable Wasm threads (SharedArrayBuffer)</a></li>
<li><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a></li>
<li><a href="/tutorials/game-physics-libraries">Game physics libraries</a> — running Rapier or Cannon-es in a Worker</li>
<li><a href="/tutorials/streaming-asset-loading">Streaming asset loading</a> — decoding assets off the main thread</li>
<li><a href="/guides/web-games-stack-2026">Web Games Tech Stack in 2026</a> — how Workers fit into the WebGL/WebGPU/Wasm stack</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">MDN: Web Workers API</a> — full API reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">MDN: Using Web Workers</a> — step-by-step guide</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects">MDN: Transferable objects</a> — zero-copy data transfer</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer">MDN: SharedArrayBuffer</a> — shared memory between threads</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebGL fundamentals for game developers]]></title>
            <link>https://app.cinevva.com/tutorials/webgl-fundamentals-for-games</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/webgl-fundamentals-for-games</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn WebGL basics for games: shaders, buffers, textures, and the render loop. Practical code you can copy and build on.]]></description>
            <content:encoded><![CDATA[<h1>WebGL fundamentals for game developers</h1>
<p>WebGL gives you direct GPU access in the browser. It's the foundation for 3D (and performant 2D) web games. This tutorial covers the essentials.</p>
<h2>1) Getting a WebGL context</h2>
<pre><code class="language-js">const canvas = document.getElementById('game')
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl')

if (!gl) {
  // Fallback or error message
  console.error('WebGL not supported')
}
</code></pre>
<p>Prefer <code>webgl2</code> when available—it's widely supported and offers better features.</p>
<h2>2) The render pipeline (simplified)</h2>
<ol>
<li><strong>Vertex shader</strong> runs once per vertex. It positions your geometry.</li>
<li><strong>Fragment shader</strong> runs once per pixel. It colors the output.</li>
<li>Buffers hold data (positions, UVs, colors).</li>
<li>Textures are images sampled by shaders.</li>
</ol>
<h2>3) A minimal shader pair</h2>
<p><strong>Vertex shader:</strong></p>
<pre><code class="language-glsl">#version 300 es
in vec2 a_position;
void main() {
  gl_Position = vec4(a_position, 0.0, 1.0);
}
</code></pre>
<p><strong>Fragment shader:</strong></p>
<pre><code class="language-glsl">#version 300 es
precision mediump float;
out vec4 fragColor;
void main() {
  fragColor = vec4(1.0, 0.5, 0.2, 1.0); // orange
}
</code></pre>
<h2>4) Compiling and linking shaders</h2>
<pre><code class="language-js">function createShader(gl, type, source) {
  const shader = gl.createShader(type)
  gl.shaderSource(shader, source)
  gl.compileShader(shader)
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    console.error(gl.getShaderInfoLog(shader))
    gl.deleteShader(shader)
    return null
  }
  return shader
}

function createProgram(gl, vs, fs) {
  const program = gl.createProgram()
  gl.attachShader(program, vs)
  gl.attachShader(program, fs)
  gl.linkProgram(program)
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    console.error(gl.getProgramInfoLog(program))
    return null
  }
  return program
}
</code></pre>
<h2>5) Creating buffers</h2>
<pre><code class="language-js">const positions = new Float32Array([
  -0.5, -0.5,
   0.5, -0.5,
   0.0,  0.5,
])

const buffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW)
</code></pre>
<h2>6) Connecting buffers to shaders</h2>
<pre><code class="language-js">const positionLoc = gl.getAttribLocation(program, 'a_position')
gl.enableVertexAttribArray(positionLoc)
gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0)
</code></pre>
<h2>7) The game loop</h2>
<pre><code class="language-js">function render() {
  gl.viewport(0, 0, canvas.width, canvas.height)
  gl.clearColor(0, 0, 0, 1)
  gl.clear(gl.COLOR_BUFFER_BIT)

  gl.useProgram(program)
  gl.drawArrays(gl.TRIANGLES, 0, 3)

  requestAnimationFrame(render)
}
render()
</code></pre>
<h2>8) Loading textures</h2>
<pre><code class="language-js">function loadTexture(gl, url) {
  const texture = gl.createTexture()
  gl.bindTexture(gl.TEXTURE_2D, texture)

  // Placeholder pixel until image loads
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
    new Uint8Array([255, 0, 255, 255]))

  const img = new Image()
  img.onload = () =&gt; {
    gl.bindTexture(gl.TEXTURE_2D, texture)
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)
    gl.generateMipmap(gl.TEXTURE_2D)
  }
  img.src = url
  return texture
}
</code></pre>
<h2>9) Common gotchas</h2>
<ul>
<li><strong>Power-of-two textures</strong> aren't strictly required in WebGL 2, but mipmaps work better with them.</li>
<li><strong>Lost context</strong>: handle <code>webglcontextlost</code> events—mobile browsers will evict contexts under memory pressure.</li>
<li><strong>Float textures</strong> need extension checks (<code>EXT_color_buffer_float</code>).</li>
</ul>
<h2>10) When to use a library</h2>
<p>Raw WebGL is verbose. For most games, consider:</p>
<ul>
<li><strong>Three.js</strong> — full-featured 3D</li>
<li><strong>PixiJS</strong> — fast 2D rendering</li>
<li><strong>PlayCanvas</strong> — game engine with editor</li>
</ul>
<p>Use raw WebGL when you need:</p>
<ul>
<li>maximum control</li>
<li>a custom renderer</li>
<li>to learn how things really work</li>
</ul>
<p>One note for 2026: WebGPU now ships by default in every major browser (Chrome and Edge since 113, Firefox 141 on Windows and 145 on macOS, and Safari on iOS 26, iPadOS 26, and macOS Tahoe 26). The fundamentals here still apply, since libraries like Three.js run their WebGPU renderer with an automatic WebGL 2 fallback, so WebGL 2 remains the dependable baseline. If you're starting a new renderer from scratch today, read the WebGPU tutorial alongside this one before committing to an API, and check what your own machine reports with the free <a href="/tools/webgl-webgpu-checker">WebGL and WebGPU checker</a> rather than trusting a support table.</p>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/webgpu-getting-started">WebGPU for games</a></li>
<li><a href="/tutorials/canvas-2d-game-loop">Canvas 2D game loop</a></li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/guides/web-games-stack-2026">Web Games Tech Stack in 2026</a> — when to pick WebGL vs WebGPU vs Wasm</li>
<li><a href="/tutorials/game-physics-libraries">Game physics libraries</a> — physics engines that render through WebGL</li>
<li><a href="/guides/web-game-engines-comparison">Web Game Engines Comparison</a> — Three.js, PixiJS, PlayCanvas, and others</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API">MDN: WebGL API</a> — full API reference</li>
<li><a href="https://webgl2fundamentals.org/">WebGL2 Fundamentals</a> — in-depth WebGL2 tutorial series</li>
<li><a href="https://thebookofshaders.com/">The Book of Shaders</a> — interactive guide to GLSL fragment shaders</li>
<li><a href="https://threejs.org/docs/">Three.js documentation</a> — the most popular WebGL framework</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebGPU getting started for game developers]]></title>
            <link>https://app.cinevva.com/tutorials/webgpu-getting-started</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/webgpu-getting-started</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Get started with WebGPU: device setup, pipelines, shaders, and rendering. Modern GPU API for the next generation of web games.]]></description>
            <content:encoded><![CDATA[<h1>WebGPU getting started for game developers</h1>
<p>WebGPU is the successor to WebGL. It's lower-level, more explicit, and designed for modern GPUs. If you're starting a new 3D project in 2026, WebGPU is worth learning.</p>
<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;border-radius:8px;margin:1.5rem 0">
<iframe src="https://www.youtube.com/embed/KTFFdZSDiTU" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0" allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture" allowfullscreen></iframe>
</div>
<p style="font-size:0.9rem;color:var(--vp-c-text-2);margin-top:-0.5rem">WebGPU Tutorial: 10 projects covering setup through 3D rendering with lighting and animation</p>
<h2>1) Check browser support</h2>
<pre><code class="language-js">if (!navigator.gpu) {
  console.error('WebGPU not supported')
}
</code></pre>
<p>As of 2026, WebGPU is available in Chrome, Edge, Firefox, and Safari. Support still varies by GPU and driver underneath that, so before you debug a blank canvas, confirm what the device reports with the free <a href="/tools/webgl-webgpu-checker">WebGL and WebGPU checker</a>.</p>
<h2>2) Get a device</h2>
<pre><code class="language-js">const adapter = await navigator.gpu.requestAdapter()
const device = await adapter.requestDevice()
</code></pre>
<p>The adapter represents the physical GPU. The device is your interface to it.</p>
<p>Both calls can fail. <code>requestAdapter()</code> returns <code>null</code> when the system has no usable GPU, and <code>requestDevice()</code> can reject, so guard against that before continuing:</p>
<pre><code class="language-js">const adapter = await navigator.gpu.requestAdapter()
if (!adapter) throw new Error('No suitable GPU adapter found')
const device = await adapter.requestDevice()
</code></pre>
<p>The adapter is also consumed once you create a device from it, so request a fresh adapter if you need another device.</p>
<h2>3) Configure the canvas</h2>
<pre><code class="language-js">const canvas = document.getElementById('game')
const context = canvas.getContext('webgpu')
const format = navigator.gpu.getPreferredCanvasFormat()

context.configure({
  device,
  format,
  alphaMode: 'premultiplied',
})
</code></pre>
<h2>4) Write shaders in WGSL</h2>
<p>WebGPU uses WGSL (WebGPU Shading Language), not GLSL.</p>
<pre><code class="language-wgsl">@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -&gt; @builtin(position) vec4f {
  var pos = array&lt;vec2f, 3&gt;(
    vec2f( 0.0,  0.5),
    vec2f(-0.5, -0.5),
    vec2f( 0.5, -0.5),
  );
  return vec4f(pos[idx], 0.0, 1.0);
}

@fragment
fn fs_main() -&gt; @location(0) vec4f {
  return vec4f(1.0, 0.5, 0.2, 1.0); // orange
}
</code></pre>
<h2>5) Create a shader module</h2>
<pre><code class="language-js">const shaderModule = device.createShaderModule({
  code: wgslSource,
})
</code></pre>
<h2>6) Create a render pipeline</h2>
<pre><code class="language-js">const pipeline = device.createRenderPipeline({
  layout: 'auto',
  vertex: {
    module: shaderModule,
    entryPoint: 'vs_main',
  },
  fragment: {
    module: shaderModule,
    entryPoint: 'fs_main',
    targets: [{ format }],
  },
})
</code></pre>
<h2>7) Render a frame</h2>
<pre><code class="language-js">function render() {
  const commandEncoder = device.createCommandEncoder()
  const textureView = context.getCurrentTexture().createView()

  const renderPass = commandEncoder.beginRenderPass({
    colorAttachments: [{
      view: textureView,
      clearValue: { r: 0, g: 0, b: 0, a: 1 },
      loadOp: 'clear',
      storeOp: 'store',
    }],
  })

  renderPass.setPipeline(pipeline)
  renderPass.draw(3)
  renderPass.end()

  device.queue.submit([commandEncoder.finish()])
  requestAnimationFrame(render)
}
render()
</code></pre>
<h2>8) Buffers in WebGPU</h2>
<pre><code class="language-js">const vertices = new Float32Array([
  -0.5, -0.5,
   0.5, -0.5,
   0.0,  0.5,
])

const vertexBuffer = device.createBuffer({
  size: vertices.byteLength,
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
})

device.queue.writeBuffer(vertexBuffer, 0, vertices)
</code></pre>
<h2>9) Bind groups for uniforms</h2>
<pre><code class="language-js">const uniformBuffer = device.createBuffer({
  size: 64,
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
})

const bindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [{
    binding: 0,
    resource: { buffer: uniformBuffer },
  }],
})
</code></pre>
<h2>10) WebGPU vs WebGL</h2>
<table>
<thead>
<tr>
<th>Aspect</th>
<th>WebGL</th>
<th>WebGPU</th>
</tr>
</thead>
<tbody>
<tr>
<td>API style</td>
<td>OpenGL-like, stateful</td>
<td>Modern, explicit</td>
</tr>
<tr>
<td>Shaders</td>
<td>GLSL</td>
<td>WGSL</td>
</tr>
<tr>
<td>Compute</td>
<td>Limited (extensions)</td>
<td>First-class support</td>
</tr>
<tr>
<td>Multi-threading</td>
<td>Difficult</td>
<td>Designed for it</td>
</tr>
<tr>
<td>Browser support</td>
<td>Universal</td>
<td>All major browsers (Chrome, Edge, Safari 26, Firefox)</td>
</tr>
</tbody>
</table>
<h2>When to use WebGPU</h2>
<ul>
<li>New projects targeting modern browsers</li>
<li>Compute-heavy workloads (physics, AI, procedural gen)</li>
<li>When you need fine-grained control over GPU resources</li>
</ul>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/webgl-fundamentals-for-games">WebGL fundamentals</a></li>
<li><a href="/tutorials/web-workers-game-logic">Web Workers for game logic</a></li>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/guides/web-games-stack-2026">Web Games Tech Stack in 2026</a> — decision framework for WebGL vs WebGPU vs Wasm</li>
<li><a href="/tutorials/coop-coep-sharedarraybuffer">COOP/COEP and SharedArrayBuffer</a> — required headers for Wasm threading with WebGPU compute</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://www.w3.org/TR/webgpu/">WebGPU specification</a> — W3C spec</li>
<li><a href="https://www.w3.org/TR/WGSL/">WGSL specification</a> — WebGPU Shading Language spec</li>
<li><a href="https://webgpufundamentals.org/">WebGPU Fundamentals</a> — in-depth tutorial series</li>
<li><a href="https://codelabs.developers.google.com/your-first-webgpu-app">Your first WebGPU app</a> — Google Codelab walkthrough</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSocket multiplayer basics]]></title>
            <link>https://app.cinevva.com/tutorials/websocket-multiplayer-basics</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/websocket-multiplayer-basics</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Build real-time multiplayer with WebSockets: connection handling, message protocols, and synchronization patterns for web games.]]></description>
            <content:encoded><![CDATA[<h1>WebSocket multiplayer basics</h1>
<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;border-radius:8px;margin:1.5rem 0">
<iframe src="https://www.youtube.com/embed/cXxEiWudIUY" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0" allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture" allowfullscreen></iframe>
</div>
<p style="font-size:0.9rem;color:var(--vp-c-text-2);margin-top:-0.5rem">Building a multiplayer game with WebSockets: server architecture, game rooms, and state sync</p>
<p>WebSockets enable real-time communication for multiplayer games. This tutorial covers the client-side fundamentals.</p>
<h2>1) Connecting to a server</h2>
<pre><code class="language-js">const ws = new WebSocket('wss://game-server.example.com')

ws.onopen = () =&gt; {
  console.log('Connected')
  ws.send(JSON.stringify({ type: 'join', name: 'Player1' }))
}

ws.onmessage = (event) =&gt; {
  const msg = JSON.parse(event.data)
  handleMessage(msg)
}

ws.onclose = () =&gt; {
  console.log('Disconnected')
}

ws.onerror = (err) =&gt; {
  console.error('WebSocket error:', err)
}
</code></pre>
<h2>2) Message protocol design</h2>
<p>Define a simple protocol:</p>
<pre><code class="language-js">// Client -&gt; Server
{ type: 'join', name: 'Player1' }
{ type: 'input', keys: { left: true, jump: true } }
{ type: 'chat', message: 'Hello!' }

// Server -&gt; Client
{ type: 'state', players: [...], entities: [...] }
{ type: 'playerJoined', id: 'abc', name: 'Player2' }
{ type: 'playerLeft', id: 'abc' }
</code></pre>
<h2>3) Connection manager class</h2>
<pre><code class="language-js">class GameConnection {
  constructor(url) {
    this.url = url
    this.ws = null
    this.handlers = new Map()
    this.reconnectDelay = 1000
  }
  
  connect() {
    this.ws = new WebSocket(this.url)
    
    this.ws.onopen = () =&gt; {
      this.reconnectDelay = 1000
      this.emit('connected')
    }
    
    this.ws.onmessage = (e) =&gt; {
      const msg = JSON.parse(e.data)
      this.emit(msg.type, msg)
    }
    
    this.ws.onclose = () =&gt; {
      this.emit('disconnected')
      this.scheduleReconnect()
    }
    
    this.ws.onerror = () =&gt; {
      this.ws.close()
    }
  }
  
  scheduleReconnect() {
    setTimeout(() =&gt; {
      this.reconnectDelay = Math.min(this.reconnectDelay * 2, 30000)
      this.connect()
    }, this.reconnectDelay)
  }
  
  send(type, data = {}) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify({ type, ...data }))
    }
  }
  
  on(type, handler) {
    if (!this.handlers.has(type)) {
      this.handlers.set(type, [])
    }
    this.handlers.get(type).push(handler)
  }
  
  emit(type, data) {
    const handlers = this.handlers.get(type) || []
    handlers.forEach(h =&gt; h(data))
  }
  
  disconnect() {
    this.ws?.close()
  }
}
</code></pre>
<h2>4) Sending player input</h2>
<p>Send inputs, not positions. Let the server be authoritative:</p>
<pre><code class="language-js">const connection = new GameConnection('wss://server.example.com')

function sendInput(input) {
  connection.send('input', {
    left: input.left,
    right: input.right,
    jump: input.jump,
    shoot: input.shoot,
    seq: inputSequence++,
  })
}

// Send input at a fixed rate (e.g., 20 times/sec)
setInterval(() =&gt; {
  sendInput(currentInput)
}, 50)
</code></pre>
<h2>5) Receiving game state</h2>
<pre><code class="language-js">let gameState = { players: [], entities: [] }

connection.on('state', (msg) =&gt; {
  gameState = msg
})

connection.on('playerJoined', (msg) =&gt; {
  gameState.players.push({ id: msg.id, name: msg.name })
})

connection.on('playerLeft', (msg) =&gt; {
  gameState.players = gameState.players.filter(p =&gt; p.id !== msg.id)
})
</code></pre>
<h2>6) Interpolation for smooth movement</h2>
<p>Server sends snapshots. Interpolate between them:</p>
<pre><code class="language-js">class EntityInterpolator {
  constructor() {
    this.buffer = [] // { timestamp, state }
    this.renderDelay = 100 // ms behind server
  }
  
  addSnapshot(timestamp, state) {
    this.buffer.push({ timestamp, state })
    
    // Keep only recent snapshots
    while (this.buffer.length &gt; 10) {
      this.buffer.shift()
    }
  }
  
  getState(currentTime) {
    const renderTime = currentTime - this.renderDelay
    
    // Find surrounding snapshots
    let before = null
    let after = null
    
    for (let i = 0; i &lt; this.buffer.length - 1; i++) {
      if (this.buffer[i].timestamp &lt;= renderTime &amp;&amp; 
          this.buffer[i + 1].timestamp &gt;= renderTime) {
        before = this.buffer[i]
        after = this.buffer[i + 1]
        break
      }
    }
    
    if (!before || !after) {
      return this.buffer[this.buffer.length - 1]?.state
    }
    
    // Interpolate
    const t = (renderTime - before.timestamp) / (after.timestamp - before.timestamp)
    return this.lerp(before.state, after.state, t)
  }
  
  lerp(a, b, t) {
    return {
      x: a.x + (b.x - a.x) * t,
      y: a.y + (b.y - a.y) * t,
    }
  }
}
</code></pre>
<h2>7) Client-side prediction</h2>
<p>For responsive controls, predict locally and reconcile with server:</p>
<pre><code class="language-js">class PredictedPlayer {
  constructor() {
    this.position = { x: 0, y: 0 }
    this.pendingInputs = []
  }
  
  applyInput(input) {
    // Apply input locally
    if (input.left) this.position.x -= 5
    if (input.right) this.position.x += 5
    
    // Store for reconciliation
    this.pendingInputs.push({ seq: input.seq, input })
  }
  
  reconcile(serverState, lastProcessedSeq) {
    // Server confirmed position
    this.position = { ...serverState.position }
    
    // Remove confirmed inputs
    this.pendingInputs = this.pendingInputs.filter(i =&gt; i.seq &gt; lastProcessedSeq)
    
    // Re-apply unconfirmed inputs
    for (const pending of this.pendingInputs) {
      if (pending.input.left) this.position.x -= 5
      if (pending.input.right) this.position.x += 5
    }
  }
}
</code></pre>
<h2>8) Handling latency display</h2>
<pre><code class="language-js">class LatencyMonitor {
  constructor(connection) {
    this.connection = connection
    this.pingStart = 0
    this.latency = 0
    
    connection.on('pong', () =&gt; {
      this.latency = Date.now() - this.pingStart
    })
    
    setInterval(() =&gt; this.ping(), 1000)
  }
  
  ping() {
    this.pingStart = Date.now()
    this.connection.send('ping')
  }
  
  getLatency() {
    return this.latency
  }
}
</code></pre>
<h2>9) Binary messages for efficiency</h2>
<p>For high-frequency updates, use binary:</p>
<pre><code class="language-js">// Sending binary
const buffer = new ArrayBuffer(12)
const view = new DataView(buffer)
view.setFloat32(0, player.x)
view.setFloat32(4, player.y)
view.setUint32(8, inputFlags)
ws.send(buffer)

// Receiving binary
ws.binaryType = 'arraybuffer'
ws.onmessage = (e) =&gt; {
  if (e.data instanceof ArrayBuffer) {
    const view = new DataView(e.data)
    const x = view.getFloat32(0)
    const y = view.getFloat32(4)
    // ...
  }
}
</code></pre>
<h2>10) Basic server example (Node.js)</h2>
<pre><code class="language-js">import { WebSocketServer } from 'ws'

const wss = new WebSocketServer({ port: 8080 })
const players = new Map()

wss.on('connection', (ws) =&gt; {
  const id = crypto.randomUUID()
  players.set(id, { id, x: 0, y: 0, ws })
  
  ws.on('message', (data) =&gt; {
    const msg = JSON.parse(data)
    
    if (msg.type === 'input') {
      const player = players.get(id)
      if (msg.left) player.x -= 5
      if (msg.right) player.x += 5
    }
  })
  
  ws.on('close', () =&gt; {
    players.delete(id)
    broadcast({ type: 'playerLeft', id })
  })
})

// Broadcast state 20 times/sec
setInterval(() =&gt; {
  const state = {
    type: 'state',
    players: Array.from(players.values()).map(p =&gt; ({
      id: p.id, x: p.x, y: p.y
    }))
  }
  broadcast(state)
}, 50)

function broadcast(msg) {
  const data = JSON.stringify(msg)
  for (const player of players.values()) {
    player.ws.send(data)
  }
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/ship-web-game-fast">Ship a web game that loads fast</a></li>
<li><a href="/tutorials/game-input-handling">Game input handling</a></li>
<li><a href="/tutorials/web-workers-game-logic">Web Workers for game logic</a></li>
<li><a href="/tutorials/coop-coep-sharedarraybuffer">COOP/COEP and SharedArrayBuffer</a> — headers needed for SharedArrayBuffer in multiplayer contexts</li>
<li><a href="/guides/co-op-game-design">Co-op Game Design in 2026</a> — why &quot;friend slop&quot; co-op games are exploding and how browser multiplayer fits in</li>
<li><a href="/guides/game-jams-hackathons">Game Jams &amp; Hackathons</a> — multiplayer jam games get more attention</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">MDN: WebSocket API</a> — browser WebSocket reference</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API">MDN: WebRTC API</a> — peer-to-peer connections for lower latency</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API">MDN: WebTransport API</a> — a newer HTTP/3 transport that reached cross-browser Baseline in March 2026 once Safari 26.4 shipped support (it was already in Chrome 97+, Edge, and Firefox 114+). Unlike a single TCP-based WebSocket, WebTransport runs over QUIC and offers unreliable datagrams plus multiple independent streams, so one dropped packet doesn't head-of-line-block everything else. A common pattern is sending high-frequency position updates over datagrams and keeping chat or scoreboards on a reliable stream. WebSockets are still the most compatible choice and everything above still applies, but WebTransport is now worth considering for latency-sensitive games.</li>
<li><a href="https://socket.io/docs/v4/">Socket.IO documentation</a> — popular WebSocket wrapper library</li>
<li><a href="https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking">Valve Source Multiplayer Networking</a> — authoritative networking patterns used in production games</li>
</ul>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebXR basics for VR games]]></title>
            <link>https://app.cinevva.com/tutorials/webxr-basics</link>
            <guid isPermaLink="true">https://app.cinevva.com/tutorials/webxr-basics</guid>
            <pubDate>Sun, 18 Jan 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Get started with WebXR: session setup, rendering, controllers, and interactions. Build VR experiences that run in the browser.]]></description>
            <content:encoded><![CDATA[<h1>WebXR basics for VR games</h1>
<p>WebXR brings VR and AR to the browser. Players can experience your game in a headset without downloading anything.</p>
<h2>1) Check WebXR support</h2>
<pre><code class="language-js">async function checkXRSupport() {
  if (!navigator.xr) {
    return { vr: false, ar: false }
  }
  
  const vr = await navigator.xr.isSessionSupported('immersive-vr')
  const ar = await navigator.xr.isSessionSupported('immersive-ar')
  
  return { vr, ar }
}

// Usage
const support = await checkXRSupport()
if (support.vr) {
  showVRButton()
}
</code></pre>
<h2>2) Starting a VR session</h2>
<pre><code class="language-js">let xrSession = null
let xrRefSpace = null

async function startVR() {
  try {
    xrSession = await navigator.xr.requestSession('immersive-vr', {
      requiredFeatures: ['local-floor'],
      optionalFeatures: ['hand-tracking'],
    })
    
    xrSession.addEventListener('end', onSessionEnd)
    
    // Set up rendering
    const gl = canvas.getContext('webgl2', { xrCompatible: true })
    await xrSession.updateRenderState({
      baseLayer: new XRWebGLLayer(xrSession, gl),
    })
    
    // Get reference space
    xrRefSpace = await xrSession.requestReferenceSpace('local-floor')
    
    // Start render loop
    xrSession.requestAnimationFrame(onXRFrame)
  } catch (err) {
    console.error('Failed to start VR:', err)
  }
}

function onSessionEnd() {
  xrSession = null
  xrRefSpace = null
}
</code></pre>
<h2>3) The XR render loop</h2>
<pre><code class="language-js">function onXRFrame(time, frame) {
  const session = frame.session
  session.requestAnimationFrame(onXRFrame)
  
  const pose = frame.getViewerPose(xrRefSpace)
  if (!pose) return
  
  const glLayer = session.renderState.baseLayer
  gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer)
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  
  // Render for each eye
  for (const view of pose.views) {
    const viewport = glLayer.getViewport(view)
    gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height)
    
    // Get camera matrices
    const viewMatrix = view.transform.inverse.matrix
    const projectionMatrix = view.projectionMatrix
    
    // Render scene with these matrices
    renderScene(viewMatrix, projectionMatrix)
  }
}
</code></pre>
<h2>4) Input sources (controllers)</h2>
<pre><code class="language-js">xrSession.addEventListener('inputsourceschange', (e) =&gt; {
  for (const source of e.added) {
    console.log('Controller added:', source.handedness) // 'left' or 'right'
  }
  for (const source of e.removed) {
    console.log('Controller removed:', source.handedness)
  }
})

function processInput(frame) {
  for (const source of xrSession.inputSources) {
    if (!source.gamepad) continue
    
    const gamepad = source.gamepad
    
    // Trigger (usually index 0)
    const triggerPressed = gamepad.buttons[0]?.pressed
    const triggerValue = gamepad.buttons[0]?.value || 0
    
    // Grip (usually index 1)
    const gripPressed = gamepad.buttons[1]?.pressed
    
    // Thumbstick
    const thumbstickX = gamepad.axes[2] || 0
    const thumbstickY = gamepad.axes[3] || 0
    
    // A/B buttons (index 4, 5)
    const buttonA = gamepad.buttons[4]?.pressed
    const buttonB = gamepad.buttons[5]?.pressed
  }
}
</code></pre>
<h3>Don't assume every device has a gamepad</h3>
<p>The code above reads <code>source.gamepad</code> for triggers and thumbsticks. That works on controller headsets like Meta Quest, but it does nothing on Apple Vision Pro (WebXR is on by default in visionOS 2 Safari) or Samsung Galaxy XR and other Android XR devices, where the primary input is gaze-and-pinch or hand tracking. On those headsets <code>source.gamepad</code> is null and <code>session.inputSources</code> stays empty until the user actually pinches.</p>
<p>For the one interaction every device guarantees, the &quot;primary action,&quot; listen for the <code>select</code> events instead of polling buttons. WebXR delivers <code>selectstart</code>, <code>select</code>, and <code>selectend</code> for a controller trigger, a hand pinch, and a Vision Pro gaze-and-pinch alike, so a single handler covers all of them:</p>
<pre><code class="language-js">xrSession.addEventListener('selectstart', (e) =&gt; {
  // e.inputSource is the controller, hand, or transient pinch
  // e.frame lets you read its targetRaySpace pose
})
xrSession.addEventListener('select', (e) =&gt; {
  // primary action completed (trigger pulled, pinch released on target)
})
xrSession.addEventListener('selectend', (e) =&gt; {})
</code></pre>
<p>Keep the gamepad code for thumbstick locomotion and extra buttons on controller headsets, but gate it behind <code>if (source.gamepad)</code> and route your core &quot;select/grab/activate&quot; interaction through these events so the game still works on hand- and gaze-driven devices.</p>
<h2>5) Controller positions</h2>
<pre><code class="language-js">function getControllerPose(frame, source) {
  if (!source.gripSpace) return null
  
  const pose = frame.getPose(source.gripSpace, xrRefSpace)
  if (!pose) return null
  
  return {
    position: pose.transform.position,
    orientation: pose.transform.orientation,
    matrix: pose.transform.matrix,
  }
}

function renderControllers(frame) {
  for (const source of xrSession.inputSources) {
    const pose = getControllerPose(frame, source)
    if (pose) {
      renderControllerModel(pose, source.handedness)
    }
  }
}
</code></pre>
<h2>6) Ray casting for pointing</h2>
<pre><code class="language-js">function getControllerRay(frame, source) {
  if (!source.targetRaySpace) return null
  
  const pose = frame.getPose(source.targetRaySpace, xrRefSpace)
  if (!pose) return null
  
  const origin = pose.transform.position
  const direction = {
    x: -pose.transform.matrix[8],
    y: -pose.transform.matrix[9],
    z: -pose.transform.matrix[10],
  }
  
  return { origin, direction }
}

function checkRayIntersection(ray, objects) {
  let closest = null
  let closestDist = Infinity
  
  for (const obj of objects) {
    const dist = rayIntersectBox(ray, obj.boundingBox)
    if (dist !== null &amp;&amp; dist &lt; closestDist) {
      closest = obj
      closestDist = dist
    }
  }
  
  return closest
}
</code></pre>
<h2>7) Teleportation locomotion</h2>
<pre><code class="language-js">class TeleportSystem {
  constructor() {
    this.targetPosition = null
    this.isAiming = false
  }
  
  update(frame, inputSources) {
    for (const source of inputSources) {
      if (source.handedness !== 'left') continue
      
      const gamepad = source.gamepad
      const thumbstickY = gamepad?.axes[3] || 0
      
      if (thumbstickY &lt; -0.5) {
        // Aiming
        this.isAiming = true
        const ray = getControllerRay(frame, source)
        this.targetPosition = this.findTeleportTarget(ray)
      } else if (this.isAiming) {
        // Release - teleport
        if (this.targetPosition) {
          player.position.x = this.targetPosition.x
          player.position.z = this.targetPosition.z
        }
        this.isAiming = false
        this.targetPosition = null
      }
    }
  }
  
  findTeleportTarget(ray) {
    // Intersect with ground plane
    if (ray.direction.y &gt;= 0) return null
    
    const t = -ray.origin.y / ray.direction.y
    if (t &lt; 0 || t &gt; 10) return null
    
    return {
      x: ray.origin.x + ray.direction.x * t,
      y: 0,
      z: ray.origin.z + ray.direction.z * t,
    }
  }
  
  render() {
    if (this.isAiming &amp;&amp; this.targetPosition) {
      renderTeleportMarker(this.targetPosition)
    }
  }
}
</code></pre>
<h2>8) Smooth locomotion</h2>
<pre><code class="language-js">function updateSmoothLocomotion(frame, inputSources, dt) {
  for (const source of inputSources) {
    if (source.handedness !== 'left') continue
    
    const gamepad = source.gamepad
    if (!gamepad) continue
    
    const moveX = gamepad.axes[2] || 0
    const moveY = gamepad.axes[3] || 0
    
    // Apply deadzone
    if (Math.abs(moveX) &lt; 0.1) moveX = 0
    if (Math.abs(moveY) &lt; 0.1) moveY = 0
    
    // Get head direction for movement
    const pose = frame.getViewerPose(xrRefSpace)
    if (!pose) continue
    
    const headMatrix = pose.transform.matrix
    const forward = { x: -headMatrix[8], z: -headMatrix[10] }
    const right = { x: headMatrix[0], z: headMatrix[2] }
    
    // Normalize to XZ plane
    const len = Math.sqrt(forward.x ** 2 + forward.z ** 2)
    forward.x /= len
    forward.z /= len
    
    const speed = 3 * dt
    player.position.x += (forward.x * -moveY + right.x * moveX) * speed
    player.position.z += (forward.z * -moveY + right.z * moveX) * speed
  }
}
</code></pre>
<h2>9) VR comfort guidelines</h2>
<pre><code class="language-js">// Vignette during movement to reduce motion sickness
function renderComfortVignette(movementSpeed) {
  const intensity = Math.min(movementSpeed / 5, 0.5)
  if (intensity &lt; 0.1) return
  
  // Render dark edges that increase with speed
  renderVignette(intensity)
}

// Snap turning
let snapTurnCooldown = 0

function handleSnapTurn(gamepad, dt) {
  snapTurnCooldown -= dt
  
  const thumbstickX = gamepad.axes[2] || 0
  
  if (Math.abs(thumbstickX) &gt; 0.7 &amp;&amp; snapTurnCooldown &lt;= 0) {
    const angle = Math.sign(thumbstickX) * (Math.PI / 4) // 45 degrees
    player.rotation += angle
    snapTurnCooldown = 0.3 // Prevent rapid turns
  }
}
</code></pre>
<h2>10) Complete WebXR setup</h2>
<pre><code class="language-js">class VRGame {
  constructor(canvas) {
    this.canvas = canvas
    this.gl = canvas.getContext('webgl2', { xrCompatible: true })
    this.session = null
    this.refSpace = null
    this.teleport = new TeleportSystem()
  }
  
  async checkSupport() {
    if (!navigator.xr) return false
    return await navigator.xr.isSessionSupported('immersive-vr')
  }
  
  async start() {
    this.session = await navigator.xr.requestSession('immersive-vr', {
      requiredFeatures: ['local-floor'],
    })
    
    await this.session.updateRenderState({
      baseLayer: new XRWebGLLayer(this.session, this.gl),
    })
    
    this.refSpace = await this.session.requestReferenceSpace('local-floor')
    this.session.addEventListener('end', () =&gt; this.onEnd())
    this.session.requestAnimationFrame((t, f) =&gt; this.onFrame(t, f))
  }
  
  onFrame(time, frame) {
    this.session.requestAnimationFrame((t, f) =&gt; this.onFrame(t, f))
    
    const dt = (time - this.lastTime) / 1000
    this.lastTime = time
    
    // Update game logic
    this.teleport.update(frame, this.session.inputSources)
    
    // Render
    const pose = frame.getViewerPose(this.refSpace)
    if (!pose) return
    
    const glLayer = this.session.renderState.baseLayer
    this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, glLayer.framebuffer)
    this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT)
    
    for (const view of pose.views) {
      const vp = glLayer.getViewport(view)
      this.gl.viewport(vp.x, vp.y, vp.width, vp.height)
      this.render(view.transform.inverse.matrix, view.projectionMatrix)
    }
    
    this.teleport.render()
  }
  
  render(viewMatrix, projectionMatrix) {
    // Your rendering code here
  }
  
  onEnd() {
    this.session = null
  }
}
</code></pre>
<h2>Related</h2>
<ul>
<li><a href="/tutorials/webgl-fundamentals-for-games">WebGL fundamentals</a></li>
<li><a href="/tutorials/webgpu-getting-started">WebGPU getting started</a></li>
<li><a href="/tutorials/game-input-handling">Game input handling</a></li>
<li><a href="/guides/web-games-stack-2026">Web Games Tech Stack in 2026</a> — where WebXR sits in the broader tech landscape</li>
<li><a href="/guides/threejs-usdc-tech-report">Three.js + USDC in the Browser</a> — loading 3D assets for XR scenes</li>
</ul>
<h2>External Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API">MDN: WebXR Device API</a> — full API reference</li>
<li><a href="https://immersiveweb.dev/">Immersive Web</a> — WebXR samples, tools, and browser support tables</li>
<li><a href="https://threejs.org/docs/#manual/en/introduction/How-to-create-VR-content">Three.js WebXR guide</a> — VR content with Three.js</li>
</ul>
]]></content:encoded>
        </item>
    </channel>
</rss>
