К основному содержанию
скилл CX Codex

threejs-scene-setup — скилл для Claude Code: настройка сцены

Настраивает базовую сцену three.js и помогает найти причины пустого или чёрного canvas. Нужен при старте проекта, ресайзе, цикле рендеринга и OrbitControls.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-scene-setup -a claude-code
Открыть на GitHub

Что делает threejs-scene-setup

Скилл собирает основу приложения на three.js: загрузку ES-модулей через import map или бандлер, Scene, PerspectiveCamera и WebGLRenderer. Он подсказывает, как добавить mesh, задать размер canvas и плотность пикселей, а также проверить сцену через материал без освещения.

Для анимации используется renderer.setAnimationLoop() и Timer, который заменяет устаревший Clock начиная с r183. Скилл разбирает ресайз: нужно изменить camera.aspect, вызвать updateProjectionMatrix() и затем обновить размер рендерера. Для управления камерой подключается OrbitControls; при включённом damping его update() вызывают в каждом кадре.

Ориентир — паттерны r186. Перед правками существующего проекта проверьте установленную версию three, потому что пути examples и addons меняются между релизами. WebGPURenderer нужен для TSL-материалов и compute shaders, но пользовательские GLSL через ShaderMaterial и onBeforeCompile с ним не переносятся.

Какие задачи решает

  • создать сцену с камерой и рендерером three.js
  • исправить чёрный или пустой canvas
  • обновить проекцию камеры при изменении окна
  • подключить OrbitControls для вращения и масштабирования
  • перейти на WebGPURenderer для TSL и compute shaders

Примеры запросов агенту

  • Настрой базовую сцену three.js в main.js с Scene, PerspectiveCamera и WebGLRenderer.
  • Почему canvas пустой? Проверь импорт three, положение камеры и цикл setAnimationLoop().
  • Добавь OrbitControls и корректный ресайз canvas при изменении размера окна.

Как установить threejs-scene-setup

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-scene-setup -a claude-code

2Вручную: положить файлы

~/.claude/skills/threejs-scene-setup/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/threejs-scene-setup/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора77

roblox-datastores Учит агента сохранять данные игрока в Roblox через DataStoreService: загрузка на входе, сохранение на выходе и в BindToClose, ретраи. Пригодится, когда прогресс теряется. CX Codex +1 5 700установок unity-input-system Скилл для Claude Code, который настраивает ввод в Unity 6.3 LTS через Input System: action maps, PlayerInput, чтение значений в C#. CX Codex +1 5 700установок unity-scriptableobjects Помогает проектировать архитектуру данных в Unity 6.3 LTS на базе ScriptableObject. Настраивает общие переменные, каналы событий и реестры без менеджеров-одиночек. CX Codex +1 5 700установок phaser-arcade-physics Настраивает перемещение, прыжки и столкновения в 2D-играх на Phaser 4 через физический движок Arcade Physics. Помогает писать контроллеры и собирать группы объектов. CX Codex +1 5 500установок threejs-materials-lighting Скилл для three.js: подбирает материал, ставит источники света, включает тени и подключает HDR-окружение, когда модель выглядит чёрной или плоской. CX Codex +1 5 500установок unity-build-pipeline Автоматизирует сборку плееров в Unity 6.3 LTS через BuildPipeline, профили сборки и консольный CI-режим. Помогает выбрать бэкенд и урезать размер билда. CX Codex +1 5 600установок pixijs-rendering Скилл для сборки слоя рендера на PixiJS v8: асинхронный Application, загрузка текстур, сцена на Container, тикер и события указателя. CX Codex +1 5 400установок unity-navmesh Скилл для ИИ-кодинга: печёт NavMesh на уровне Unity и водит NPC по маршруту через NavMeshAgent. Пригодится, когда враг должен догонять игрока, а не стоять на месте. CX Codex +1 5 500установок

Похожие

threejs-fundamentals CloudAI-X Помогает настроить базовую сцену Three.js r186: рендерер, камеры, цикл анимации с THREE.Timer и import map для WebGL или WebGPU с TSL. CX Codex +1 17 400установок threejs-interaction CloudAI-X Скилл учит агента настраивать выбор объектов, перемещение по плоскости и управление камерой в three.js для WebGL и WebGPU. CX Codex +1 14 300установок threejs-webgl freshtechbro Скилл учит агента настраивать сцены Three.js, рендереры WebGL и WebGPU, свет, материалы и загрузку glTF-моделей. Пригодится для 3D-визуализаций и конфигураторов. CX Codex +1 4 600установок threejs mrgoonie Скилл для ИИ-кодинга, который помогает собирать 3D-сцены, шейдеры и VR-опыты на Three.js. Пригодится, когда проект упирается в WebGL или WebGPU. CX Codex +1 1 200установок threejs-game OpusGameLabs Задаёт структуру проекта и обязательные модули для 3D-игры в браузере на Three.js. Пригодится, когда агенту нужно развернуть сцену и игровой цикл с нуля. CX Codex +1 1 100установок webgpu-threejs-tsl dgreenheck Помогает писать Three.js-приложения с WebGPU, TSL-материалами, вычислительными шейдерами и постобработкой. CX Codex +1 1 600установок

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о threejs-scene-setup

Как установить threejs-scene-setup в Claude Code?

Выполните npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-scene-setup -a claude-code, затем повторите npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill threejs-scene-setup -a claude-code. Файл скилла находится в ~/.claude/skills/threejs-scene-setup/SKILL.md.

Что делает threejs-scene-setup?

Скилл помогает собрать и отладить базовую сцену three.js: импорты, камеру, рендерер, цикл отрисовки, ресайз и OrbitControls. Он также разбирает типичные причины пустого canvas.

Когда выбирать WebGPURenderer вместо WebGLRenderer?

WebGLRenderer остаётся вариантом по умолчанию для совместимости. WebGPURenderer выбирают, когда проекту нужны TSL node materials или compute shaders; перед прямым render() либо compute() требуется await renderer.init().

Исходный текст

SKILL.md · Apache-2.0
---
name: threejs-scene-setup
description: >
  Stand up a three.js scene: import maps and the three/addons path, the
  Scene/PerspectiveCamera/WebGLRenderer trio, the setAnimationLoop render loop,
  responsive resize, OrbitControls, and opting into WebGPURenderer. Use when
  starting or debugging a three.js app — when the user mentions three.js,
  THREE.Scene, WebGLRenderer, WebGPURenderer, PerspectiveCamera, the render loop,
  resizing, or OrbitControls. For models use
  threejs-gltf-loading; for materials/lights use threejs-materials-lighting.
---

# three.js Scene Setup

Create the foundation of a three.js app: module loading, the
scene/camera/renderer trio, the render loop, responsive resizing, and camera
controls. Patterns target **r186**. Read the installed `three` version before
changing an existing project because examples and addons move across releases.

## When to use

- Use when bootstrapping a three.js scene, fixing a blank/black canvas, making the
  canvas responsive, setting up the animation loop, or adding `OrbitControls`.
- Use when `package.json` depends on `three` and code does `import * as THREE from
  'three'`.

**When *not* to use:** loading `.gltf`/`.glb` models or skinned animation →
`threejs-gltf-loading`. Materials, lights, shadows, environment maps →
`threejs-materials-lighting`. 2D rendering → `pixijs-rendering`.

## Core workflow

1. **Load three.js as an ES module with an import map.** Since r137 the bare
   specifier `'three'` must be resolved by an import map (in HTML) or a bundler;
   map `'three/addons/'` too. Addons (controls, loaders) live under
   `three/addons/...`.
2. **Create the trio.** A `Scene` (root of the graph), a `PerspectiveCamera(fov,
   aspect, near, far)` moved back from the origin, and a `WebGLRenderer` whose
   `domElement` is in the DOM. Set size and `pixelRatio`.
3. **Add a mesh.** `new Mesh(geometry, material)` and `scene.add(mesh)`. With a
   lit material you also need a light (see `threejs-materials-lighting`).
4. **Drive a render loop with `renderer.setAnimationLoop(fn)`.** It's the modern,
   WebXR-/WebGPU-safe replacement for hand-rolled `requestAnimationFrame`. Use a
   `Timer` for delta time (`Clock` is deprecated since r183).
5. **Handle resize** so the camera aspect and renderer match the canvas; update
   `camera.aspect`, call `updateProjectionMatrix()`, and `renderer.setSize(...)`.
6. **Add `OrbitControls`** for orbit/pan/zoom while developing. Confirm something
   actually renders (a lit cube, the controls responding) before assuming success.

## Patterns

### 1. HTML import map + module entry (no bundler)

```html
<canvas id="c"></canvas>
<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"
  }
}
</script>
<script type="module" src="./main.js"></script>
```

With a bundler (Vite/webpack), skip the import map and just
`npm i three`; the same `import` statements resolve.

### 2. Scene + camera + renderer

```js
// main.js
import * as THREE from 'three';

const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // cap for perf
renderer.setSize(window.innerWidth, window.innerHeight);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101018);

const camera = new THREE.PerspectiveCamera(
  60,                                   // vertical field of view (degrees)
  window.innerWidth / window.innerHeight, // aspect
  0.1,                                  // near
  100                                   // far
);
camera.position.set(3, 2, 5);
camera.lookAt(0, 0, 0);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshNormalMaterial()        // unlit; shows orientation without a light
);
scene.add(cube);
```

### 3. The render loop (setAnimationLoop + Timer)

```js
const timer = new THREE.Timer();        // replaces the deprecated THREE.Clock (r183+)
timer.connect(document);                // optional: no huge delta after a hidden tab

renderer.setAnimationLoop((time) => {
  timer.update(time);                   // call once per frame, before getDelta()
  const dt = timer.getDelta();          // seconds since last frame
  cube.rotation.x += dt;                // frame-rate independent
  cube.rotation.y += dt * 0.7;
  renderer.render(scene, camera);
});
// renderer.setAnimationLoop(null); // stop the loop
```

### 4. Responsive resize

```js
function onResize() {
  const w = window.innerWidth, h = window.innerHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();      // required after changing aspect
  renderer.setSize(w, h);
}
window.addEventListener('resize', onResize);
```

### 5. OrbitControls (orbit / pan / zoom)

```js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;          // inertial feel
controls.target.set(0, 0, 0);

renderer.setAnimationLoop(() => {
  controls.update();                    // needed every frame when damping is on
  renderer.render(scene, camera);
});
```

### 6. Opting into WebGPURenderer (only when you need it)

`WebGLRenderer` stays the default choice for compatibility. Switch to
`WebGPURenderer` when the project needs TSL node materials or compute shaders; it
falls back to a WebGL 2 backend where WebGPU is unavailable.

```js
// Official WebGPU examples map both "three" and "three/webgpu" to
// build/three.webgpu.js, plus "three/tsl" to build/three.tsl.js.
import * as THREE from 'three/webgpu';

const renderer = new THREE.WebGPURenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
await renderer.init();                  // required before direct render()/compute()

renderer.setAnimationLoop(() => renderer.render(scene, camera));
```

Scenes, cameras, built-in `Mesh*Material`s, and most addons carry over; custom
GLSL (`ShaderMaterial`, `onBeforeCompile`) does not.

## Pitfalls

- **`Failed to resolve module specifier "three"`** → missing import map (or bundler
  config). Map both `"three"` and `"three/addons/"`; addon paths must end with `/`.
- **Black canvas, no errors** → camera is at the origin (inside/behind the object),
  or you used a lit material (`MeshStandardMaterial`) with no light. Move the camera
  back; use `MeshNormalMaterial`/`MeshBasicMaterial` to verify geometry first.
- **Nothing animates** → you never called `renderer.render` inside the loop, or you
  call `setAnimationLoop` but render outside it.
- **Stretched / squashed view on resize** → you resized the renderer but didn't
  update `camera.aspect` + `updateProjectionMatrix()`.
- **Blurry or jagged on HiDPI** → set `renderer.setPixelRatio(...)`; cap it (≈2) so
  4K/retina screens don't tank performance.
- **OrbitControls feel dead** → with `enableDamping = true` you must call
  `controls.update()` every frame.
- **Old tutorials use `<script src="three.min.js">` or `examples/js/...`** →
  `examples/js` was removed in r148 and `build/three.min.js` in r161; use
  `type="module"` + import maps.
- **`.render() called before the backend is initialized`** (WebGPURenderer) → call
  `await renderer.init()` before any direct `render()`/`compute()`, or render only
  from `setAnimationLoop`, which initializes first.
- **`Material "ShaderMaterial" is not compatible`, or an `onBeforeCompile` patch is
  ignored** (WebGPURenderer) → it renders node materials only; port the effect to
  TSL, or stay on `WebGLRenderer`.

## References

- For coordinate conventions, the scene-graph (`Group`, parent/child transforms,
  `Object3D` add/remove), `OrthographicCamera` for 2.5D, and disposing of
  geometries/materials/textures to avoid leaks, read `references/scene-graph.md`.

## Related skills

- `threejs-materials-lighting` — give surfaces a lit look (lights, shadows, PBR).
- `threejs-gltf-loading` — load 3D models and play their animations.
- `pixijs-rendering` — 2D rendering in the browser.
- `fps-shooter` — a 3D genre template that composes three.js skills.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой