Use this skill for 2D dynamic lighting in melonJS — Light2d, ambient light on a Stage, multiple lights, and per-pixel normal-mapped sprites authored in SpriteIlluminator. Covers specular highlights via shininess, the ambient-cutout model, which parts need a GPU backend, and why Light2d does not survive a Camera3d. Triggers on: Light2d, softness, soft light, lightHeight, setRadii, specular, shininess, highlight, glint, lighting, ambientLight, ambientLightingColor, normalMap, SpriteIlluminator, per-pixel lighting, drawLight, torch, glow, darkness.
Capabilities
The model: ambient darkness plus cutouts
The Stage holds an ambient colour — a dark sheet painted over the…
Soft edges: softness
A light's hole in the darkness is hard-edged by default: full light…
Multiple lights
Add as many as you need — the glow quads and the ambient cutouts…
Per-pixel lighting with normal maps
For sprites that respond to light direction rather than just…
Getting started
Full instructionsInstall the skill, then ask your AI tool for the task in plain words. The full SKILL.md below shows what it covers.
Instructions: SKILL.mdv1.0.3
2D dynamic lighting
Light2dis a world renderable that cuts through a stage's ambient darkness.
The glow and the cutout work on every backend; only per-pixel normal-map
shading needs a GPU one. It is 2D-only.
The model: ambient darkness plus cutouts
The Stage holds an ambient colour — a dark sheet painted over the scene after
the world is drawn — and each active Light2d punches a hole in it at its
visible area. The lights themselves are drawn additively on top.
class PlayScreen extends Stage {
onResetEvent(app) {
this.ambientLight.parseCSS("#1a1a2e"); // the darkness
app.world.addChild(new Light2d(x, y, radiusX, radiusY, "#ffddaa", 0.9));
}
}
The constructor is Light2d(x, y, radiusX, radiusY = radiusX, color = "#FFF", intensity = 0.7), and pos is the light's centre — its anchorPoint is
(0.5, 0.5), and centerX / centerY are overridden to return pos directly.
Give radiusY a different value for a stretched, elliptical light.
Resize a light with light.setRadii(radiusX, radiusY), which resizes its
bounds too. Writing radiusX alone changes nothing you can see: the glow, the
hole in the darkness and the normal-map shading are all sized from the bounds,
on every backend.
A Light2d added to the world registers itself with the stage's ambient
overlay on activate, so you add it like any other renderable and it takes part
in the lighting pass. It draws additively (blendMode = "lighter"); set
light.illuminationOnly = true to suppress the visible glow while still lighting
normal-mapped sprites.
Stage.ambientLight defaults to fully transparent black, and drawLighting()
returns immediately while its alpha is 0 — so with no ambient colour set there
is nothing to cut through and the lights just look like soft additive blobs.
Soft edges: softness
A light's hole in the darkness is hard-edged by default: full light inside its
radius, full darkness outside. light.softness (0 to 1) fades it instead:
const torch = new Light2d(x, y, 220, 220, "#ffb46a", 0.4);
torch.softness = 0.8; // lit core of 20% of the radius, then fading out
1thins the darkness straight from the centre to the edge, the same falloff
as the glow; in between, a fully lit core of1 - softnessof the radius.- Hard and soft lights mix in one scene. Where lights overlap, what is left of the
darkness is what each leaves, multiplied, so two half-lights make three
quarters light. - The hole is the light's size. For an opening wider than the glow (a torch whose
light reaches further than its flame's halo), add a second, bigger light with
illuminationOnly = true: it cuts the darkness and draws nothing. - Up to 32 lights in view are cut by one soft pass; lights outside the view do not
count. A scene with no soft light draws exactly as before. - To keep a camera out of the darkness (a minimap showing the level lit),
overridedrawLightingon the stage and skip that camera. - To keep one light out of a camera, put it, or a container it is in, on a
visibilityLayerthe camera'scullMaskleaves out: there it neither glows,
nor cuts the darkness, nor lights normal-mapped sprites (see
melonjs-camera-and-drawing). This is for aLight2d: aLight3dlights
the meshes of every camera.
Multiple lights
Add as many as you need — the glow quads and the ambient cutouts accumulate with
no fixed cap.
The normal-map pipeline is capped: lights are packed into a std140 uniform
block sized for MAX_LIGHTS = 32, and anything past the 32nd is silently dropped
from the per-pixel shading (it still draws its glow and punches its cutout). The
cap is an allocation, not a budget — the fragment loop still runs once per pixel
per live light.
Lights are positioned like any renderable, so they can follow an entity by
updating pos, or be added as children of one.
Per-pixel lighting with normal maps
For sprites that respond to light direction rather than just brightness, supply a
normal map alongside the diffuse texture:
await loader.preload([
{ name: "hero", type: "image", src: "data/img/hero.png" },
{ name: "hero_n", type: "image", src: "data/img/hero_n.png" },
]);
const hero = new Sprite(x, y, {
image: "hero",
normalMap: "hero_n", // ← enables per-pixel lighting on this sprite
framewidth: 32, frameheight: 32,
});
normalMap takes a loader key, or any image-like source (HTMLImageElement,
canvas, ImageBitmap, a Texture2d). Assigning anything else — including an
HTMLVideoElement, which would freeze on frame 0 — throws a TypeError.
It is lit on the GPU renderers, WebGL and WebGPU. On Canvas the sprite is
drawn unlit and a warning says so once (see "What needs a GPU backend" below).
A normal map is a still image, uploaded once. A sprite that animates takes
its normals from one static sheet laid out exactly like its colour sheet: the
animation picks the frame, and the same region of both is sampled. There is no
video or per-frame normal source to set up.
How grazing the light is comes from light.lightHeight, its height above the
sprite plane in the same units as its radius (default max(radiusX, radiusY) * 0.075). Lower it for light raking across the surface, which shows the relief
off; raise it for flatter, more even shading.
Normal maps are typically authored in SpriteIlluminator. The sidecar pattern
above — one _n image beside each diffuse image — is the simplest setup, but an
atlas can carry one too: new TextureAtlas(json, image, { normalMap }) pairs a
normal texture sharing the colour texture's UVs, and a Sprite built from that
atlas picks it up in preference to its own settings.normalMap.
Specular highlights
A normal map gives a sprite shape: the light knows which way each texel
faces, so a torch reveals bumps and crevices. shininess decides whether it
also shines:
const sword = new Sprite(x, y, {
image: "sword",
normalMap: "sword_n",
shininess: 64, // 0 (the default) is matte
});
The difference is what the highlight does. Diffuse brightness depends only on
the angle between the surface and the light, so a torch moving past just makes
the sprite brighter. A specular highlight only appears where a texel reflects
the light toward the screen, so it slides across the surface as the light
moves: armour that glints as you walk by, rather than armour that is merely lit.
Low values give a broad sheen (worn metal, wet stone); high values a tight glint
(polished steel, glass). It is gated on the exponent exactly as MTL Ns is on
the 3D path, so 0 means matte however bright the scene, and a sprite that
never sets it renders exactly as it always did.
Three things worth knowing:
- It needs a
normalMap. With no surface directions there is nothing to
reflect, and the sprite stays matte whatevershininesssays. - The normal map's alpha channel masks it per texel. 255 is fully
reflective, 0 is dead matte, so one sprite can be a shiny blade with a matte
leather grip. A normal map with no alpha detail (the usual case) shines
uniformly. Note the corollary: if your normal map already uses alpha for
something, that channel now also decides gloss. The mask is in the normal
map's alpha, never the colour image's: making the grip transparent there
would hide it, not dull it. - It accumulates per light. Each light contributes its own highlight in its
own colour, so a sprite between a warm lamp and a cool one carries two
distinct glints that move independently.
The highlight takes the light's own colour and is added on top of the lit
result rather than multiplied into it, which is why a glint blows out toward
white on a dark sprite instead of tinting with it.
A matte texel still needs its direction
In a normal map the alpha is a material, not a hole. A texel with an alpha of 0
is matte, and is still shaded by the direction in its RGB. That direction has to
survive all the way to the GPU, and image tools are built to assume the opposite
(that nothing matters under a transparent pixel):
| the normal map comes from | directions under a low alpha |
|---|---|
| an image file through the loader (a PNG) | kept: the engine uploads normal maps with premultiplied alpha off |
createImageBitmap(source, { premultiplyAlpha: "none" }) |
kept: the way to build a masked normal map in code |
createImageBitmap(source), default options |
wrong as soon as the alpha is below 255: WebGL uploads a bitmap as it was made, so the directions arrive multiplied by the mask |
a canvas you drew or putImageData into |
lost at an alpha of 0, and rounded at a low one: a canvas stores its pixels multiplied by their alpha |
// a masked normal map made in code: from pixels, never through a canvas
const pixels = new ImageData(width, height);
// ... rgb = the direction, a = how much it shines ...
sprite.normalMap = await createImageBitmap(pixels, { premultiplyAlpha: "none" });
Before the file reaches the game, the same goes for the pipeline: an optimiser
or a packer that "cleans" or "bleeds" the colour of fully transparent pixels, or
that premultiplies, erases the directions of every matte texel. Export the
normal sheet with those options off, and with the same layout as the colour one.
See it running: Normal Map example.
Unlit areas of a normal-mapped sprite render pure black unless you raise
Stage.ambientLightingColor (default black) — that is the base level added to
every lit pixel, and it is a different knob from Stage.ambientLight.
Without a normal map a sprite is not shaded at all: it takes the unlit path on
every backend, and a light changes how it looks only through its additive glow
and its cutout in the ambient darkness.
What needs a GPU backend, and what does not
Less than you would expect. Light2d is renderer-agnostic: it just calls
renderer.drawLight(this), and every backend implements it — the GPU backends
through a shared procedural radial-falloff shader, the Canvas renderer by
rasterising a cached Gradient into one shared render target and compositing it
with drawImage. The hard ambient cutout pass is plain setMask + fillRect;
the soft one is one shader pass on the GPU backends and an offscreen canvas on
Canvas. So the lit-spot look, soft or hard, works everywhere, Canvas included.
What Canvas cannot do is per-pixel normal-map lighting:
renderer.setLightUniforms() is a no-op there, and the first normal-mapped
sprite drawn while lights are on logs a one-shot warning (a scene with lights
and no normal maps stays quiet). Normal-mapped sprites simply render unlit — no
error.
if (app.renderer.shaderLanguage === null) {
// Canvas fallback: lights and ambient still work, but `normalMap` is ignored
}
Do not combine with Camera3d
Camera3d extends Camera2d and therefore still runs the 2D lighting pass, but
nothing in that pass is projection-aware: the ambient fill is a screen-space
fillRect, the cutout is a 2D Ellipse mask, and light positions are packed as
2D world coordinates minus the camera translate. Under a perspective projection
none of that lines up with what the camera actually draws.
For 3D scenes use Light3d instead — it is the counterpart for the mesh
lighting path, with "directional", "ambient", "point" and "spot" types.
See the melonjs-3d skill.
Symptom → cause
| symptom | cause |
|---|---|
| lights added but the scene never darkens | no ambient colour set — ambientLight alpha is 0, so the pass returns early |
| the lit area has a hard rim | softness is 0 (the default): set it on the light |
| the darkness opens no wider than the glow | the hole is the light's size: add a bigger illuminationOnly light for the opening |
| a minimap or second camera is dark too | every camera draws the stage's darkness: override drawLighting and skip that camera |
| a light should show in one camera only | put it on a visibilityLayer the other camera's cullMask leaves out |
| sprite not shaded by a light, only glowed over | no normalMap on the sprite, or the Canvas backend is active |
| normal-mapped sprite is pure black where unlit | Stage.ambientLightingColor left at black |
| the 33rd light shades nothing | MAX_LIGHTS = 32 for the normal-map pipeline |
changing radiusX / radiusY does nothing |
everything is sized from the bounds, which setRadii() updates and a bare field write does not |
| normal-mapped relief looks flat under a light | lightHeight is high relative to the radius; lower it for a grazing light |
TypeError assigning normalMap |
not an image-like value (a video element is rejected outright) |
| the whole sprite glints, not just the metal | the normal map is opaque, which is a full mask: paint the matte parts with a lower alpha in the normal map |
shininess is set and nothing glints |
no normalMap, an alpha of 0 over the whole normal map, the light behind the surface, or the Canvas backend |
| the matte part of a sprite (normal alpha 0) is black, or lit from the wrong side | its directions were erased: an optimiser cleared the colour of transparent pixels, or the map came from a canvas or from createImageBitmap with its default options. Load the file as it was exported, or build it with premultiplyAlpha: "none" |
| an animated sprite's shading does not follow its pose | the normal sheet is not laid out like the colour sheet: same size, same frames in the same places |
| lighting misaligned under a 3D camera | the 2D light pass is not projection-aware — use Light3d |
Related skills
melonjs-3d—Light3dfor perspective scenesmelonjs-sprites-and-animation— sprite settings and atlases
Explore more skills
Browse all- Melonjs PlatformsUse this skill when a melonJS game runs somewhere other than a plain browser tab: a game portal (YouTube Playables,…
- melonjsUse this skill FIRST for any melonJS task, and when asked to build a game for the browser with no engine named; it says…
- Melonjs TilemapsUse this skill for tile maps in melonJS: Tiled maps, LDtk levels, Sprite Fusion maps, and tile layers built in code.…
- Melonjs Particles and TrailsUse this skill for particle effects and motion trails in melonJS — ParticleEmitter configuration, burst versus stream…
- Melonjs Sprites and AnimationUse this skill when creating sprites, playing frame animations, or working with texture atlases in melonJS. Covers…
- Melonjs Getting StartedUse this skill when starting or bootstrapping a melonJS game, creating the Application, choosing a renderer, or setting…
Security
Reviews (0)
More from melonJS
View source →Frequently asked questions about melonjs-lighting
What does the melonjs-lighting skill do?
Use this skill for 2D dynamic lighting in melonJS — Light2d, ambient light on a Stage, multiple lights, and per-pixel normal-mapped sprites authored in SpriteIlluminator. Covers specular highlights via shininess, the ambient-cutout model, which parts need a GPU backend, and why Light2d does not survive a Camera3d. Triggers on: Light2d, softness, soft light, lightHeight, setRadii, specular, shininess, highlight, glint, lighting, ambientLight, ambientLightingColor, normalMap, SpriteIlluminator, per-pixel lighting, drawLight, torch, glow, darkness. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.
How do I install the melonjs-lighting skill?
Run `npx @skills-hub-ai/cli install melonjs-lighting` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/melonjs-lighting/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.
Which AI tools does melonjs-lighting work with?
melonjs-lighting runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.
Is the melonjs-lighting skill free?
Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.
How do I use melonjs-lighting after installing it?
In Claude Code, type `/melonjs-lighting` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.
Can I share the melonjs-lighting skill with my team?
Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.
Badge for your README
Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.
[](https://skills-hub.ai/skills/melonjs-lighting)<a href="https://skills-hub.ai/skills/melonjs-lighting"><img src="https://skills-hub.ai/api/badges/skill/melonjs-lighting" alt="Install on Skills Hub"></a>More options in the badge docs.