본문으로 건너뛰기
cccskills
무료GitHub에 공개

melonjs-getting-started

Set up a melonJS 20.x game by initializing its Application, choosing a renderer, adding objects to the world, and creating scenes. The guide also explains how renderer differences affect which visual features are available.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Use this skill when starting or bootstrapping a melonJS game, creating the Application, choosing a renderer, or setting up the first scene. Covers the mandatory async init, the world container, adding renderables, and the WebGPU/WebGL 2/Canvas fallback. Triggers on: melonjs, new Application, app.init, app.world, video.AUTO, video.WEBGL, video.CANVAS, Stage, state.change, getting started, bootstrap.

melonjs/melonJS스타 6,429(GitHub 6,429 + cccskills 0)

실행 점수 미검증

설치 방법 보기

이럴 때 유용합니다

  • Starting a new melonJS 20.x game
  • Fixing a blank screen after creating an Application
  • Choosing a renderer for different environments
  • Adding content and switching between scenes

포함된 파일(1)

  • SKILL.md6.9 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Getting started with melonJS

Bootstrapping a melonJS 20.x game: the Application lifecycle, the mandatory await app.init(), the world container, and what the renderer fallback means for feature availability.

Applies to: melonJS 20.x. Older major versions differ — see the melonjs-20-migration skill.

The bootstrap

Application construction is synchronous but initialisation is not. init() returns a promise and must be awaited before building any renderable, loading assets, or entering a scene.

import { Application, Text } from "melonjs";

const app = new Application(1218, 562, {
    parent: "screen",      // id of the DOM element to mount into
    scale: "auto",
    backgroundColor: "#202020",
});
await app.init();          // ← REQUIRED. Nothing below works without it.

app.world.addChild(
    new Text(609, 281, {
        font: "Arial",
        size: 160,
        fillStyle: "#FFFFFF",
        textAlign: "center",
        textBaseline: "middle",
        text: "Hello World !",
    }),
);

This is the single most common thing to get wrong. On 19.x the constructor called init(width, height, options) for you; on 20.x init() takes no arguments and calling — and awaiting — it is your job. Nothing that follows names the missing call. The constructor does build app.world, so adding a plain renderable succeeds and simply never draws — no canvas is appended and the app never subscribes to the frame tick — while constructing a Sprite or a Text throws Cannot read properties of undefined (reading 'renderer'), because the global game those two fall back on is only set once the first init() resolves. Either way app.renderer and app.viewport stay undefined and the page stays blank.

init() is asynchronous because acquiring a WebGPU device is asynchronous. There is no synchronous alternative.

Top-level await

The bootstrap needs await at module scope. In an ES module that is fine. If the surrounding tooling does not allow it, wrap it:

async function main() {
    const app = new Application(800, 600, { parent: "screen" });
    await app.init();
    // …
}
void main();

Choosing a renderer

video.AUTO (the default) tries WebGPU → WebGL 2 → Canvas and uses the first that works.

import { video } from "melonjs";

const app = new Application(800, 600, {
    parent: "screen",
    renderer: video.AUTO,      // default; or video.WEBGPU / video.WEBGL / video.CANVAS
});

Two consequences worth knowing before writing rendering code:

  • Which backend you get is a runtime fact, not a build-time one. The same code runs on a different renderer depending on the machine. Do not assume WebGL.
  • Not every feature exists on every backend. Shader effects and post effects need a programmable pipeline and are inert on Canvas. Where a feature degrades, the engine warns once rather than throwing — so a missing effect is a console warning, not a crash.

Pin the renderer explicitly (video.WEBGL) only when you have a reason to. It costs you the WebGPU path and the Canvas fallback.

The scene graph

app.world is the root Container. Everything drawn is a descendant of it.

app.world.addChild(sprite, 10);   // 10 is the z / draw order

Pass the z-order as the second argument to addChild — it is the only form that works. renderable.z does not exist as a property, setting depth before addChild is overwritten by autoDepth, and setting it afterwards does not resort. See the melonjs-renderables skill for the full explanation.

Scenes

For anything beyond a single screen, use Stage subclasses and the state manager rather than mutating app.world directly:

import { Stage, state } from "melonjs";

class PlayScreen extends Stage {
    onResetEvent() { /* build the scene */ }
    onDestroyEvent() { /* tear it down */ }
}

state.set(state.PLAY, new PlayScreen());
state.change(state.PLAY);

onResetEvent runs every time the state is entered, not once — build scene content there, not in the constructor.

Loading assets

Assets are declared and preloaded through loader; audio needs audio.init() with the formats you ship before any audio asset is preloaded.

import { audio, loader } from "melonjs";

loader.setOptions({ crossOrigin: "anonymous" });   // needed for remote assets
audio.init("mp3,ogg");                             // BEFORE preloading audio
await loader.preload([
    { name: "tileset", type: "image", src: "data/img/tileset.png" },
    { name: "jump",    type: "audio", src: "data/sfx/" },   // directory, not file
]);

Two ordering rules that produce confusing failures when missed:

  • audio.init() must run before any audio asset is preloaded, and names the formats you actually ship. Preloading first throws "target audio extension(s) should be set through me.audio.init() before calling the preloader".
  • The audio src is a directory, not a file. The loader appends the asset name plus each configured extension, so a full filename gives you a 404.

anchorPoint defaults to the centre

Renderable.anchorPoint is (0.5, 0.5), so pos is an object's centre, not its top-left. Container forces (0, 0) instead.

Writing top-left math against a centred anchor puts everything half a sprite off with no error — it is the most common source of "close but subtly wrong" placement.

Common mistakes

symptomcause
blank page, nothing drawn, or a TypeError reading renderer from new Sprite / new Textmissing await app.init()
objects draw in the wrong order.z/depth set instead of addChild(child, z) — .z is not even a real property
shader/post effect does nothing, warning in consolerunning on the Canvas renderer
audio 404saudio asset src given as a file rather than a directory
scene content appears once and never resetsscene built in the constructor instead of onResetEvent
everything offset by half a spritetop-left math against the centred anchorPoint default
a Tween or ParticleEmitter does nothing.start() / streamParticles() never called
cross-origin textures fail to loadmissing loader.setOptions({ crossOrigin: "anonymous" })

Related skills

  • melonjs-20-migration — what changed in 20.x that older code and older training data get wrong
  • melonjs-renderables — custom Renderable subclasses, pointer events, post effects and the traps in each

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

melonjs

무료

Use this entry point to find the melonJS guide for a game development task, from application setup and scenes to sprites, input, physics, audio, and 3D. It also points to companion packages and the API index when the guides do not cover a need.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Choose a guide for a melonJS game task
  • Find the right setup steps for a new game
  • Locate guidance for a 3D scene or imported model
melonjs/melonJS6.4천2026년 10월 29일 업데이트

Update older melonJS code for version 20.x. Review the asynchronous Application setup, renderer changes, post-effect API, and deprecated exports so you can identify outdated patterns when migrating or debugging expected APIs.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Migrating a game from melonJS 19.x
  • Checking why an older API is missing
  • Replacing deprecated shader assignments
melonjs/melonJS6.4천2026년 10월 29일 업데이트

Build 3D or 2.5D scenes in melonJS with cameras, meshes, billboards, lights, shadows, and depth sorting. This guide explains the engine’s Y-down and +Z-forward coordinates, camera setup, transparency, and fog, and identifies features that require a GPU renderer instead of the Canvas fallback.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Setting up a Camera3d for a game stage
  • Placing meshes, billboards, or repeated instances
  • Fixing depth order or transparency in a 3D scene
melonjs/melonJS6.4천2026년 10월 29일 업데이트

Load glTF, GLB, or OBJ/MTL assets into melonJS and understand how their materials, lights, animations, shadows, and instances are handled. The guide explains loader options and common format limitations so you can configure scenes and diagnose missing or incorrectly rendered asset features.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Loading a glTF or GLB scene into a melonJS level
  • Adding a static OBJ model with its MTL material
  • Checking why imported materials or lights look different
melonjs/melonJS6.4천2026년 10월 29일 업데이트

Manage sound in melonJS games: load audio, play effects and looping background tracks, control volume, and place sounds in the game world. It also covers generated tones and noise, whole-mix effects, and common causes of silent playback.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Loading sound files and choosing supported audio formats
  • Playing sound effects and looping background music
  • Positioning sounds around a player or game object
melonjs/melonJS6.4천2026년 10월 29일 업데이트

Use this skill to control melonJS cameras and draw shapes, lines, and gradients. It covers target following, camera bounds and effects, coordinate conversion, clipping, rendering into a canvas target, and reading rendered pixels for images or data.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Making a camera follow a player within world bounds
  • Converting pointer or 3D positions to screen coordinates
  • Drawing shapes or gradients in a custom draw method
melonjs/melonJS6.4천2026년 10월 29일 업데이트

melonjs의 스킬 모두 보기

이 스킬의 문제 신고