Logo di Threejs Core Raycaster

Threejs Core Raycaster

Organizzazione
Impertio-Studio
threejs-core-raycaster

Use when implementing mouse picking, hover detection, object selection, or line-of-sight checks in Three.js. Prevents the common mistake of raycasting every mousemove frame, not using layers for filtering, or missing recursive flag. Covers Raycaster, setFromCamera, intersection format, InstancedMesh picking, layers, performance. Keywords: Raycaster, mouse picking, intersectObjects, click, hover, setFromCamera, intersection, instanceId, object selection, click on 3D object, detect mouse over, pick element.

Panoramica

AutoreImpertio-Studio
RepositoryThree.js-Claude-Skill-Package
Nome della skillthreejs-core-raycaster
Stelle
29
Fork
3
File inclusi
3
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • 3 file inclusi

    Script, modelli di documento e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da Impertio-Studio su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Threejs Core Raycaster in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package/tree/master/skills/source/threejs-core/threejs-core-raycaster
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package.git /tmp/Three.js-Claude-Skill-Package
mkdir -p .claude/skills
cp -r /tmp/Three.js-Claude-Skill-Package/skills/source/threejs-core/threejs-core-raycaster .claude/skills/threejs-core-raycaster
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Threejs Core Raycaster in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Threejs Core Raycaster non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Threejs Core Raycaster non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

threejs-core-raycaster

Quick Reference

Raycaster Constructor

javascript
import * as THREE from 'three';

const raycaster = new THREE.Raycaster(
  origin,     // Vector3 — default: (0, 0, 0)
  direction,  // Vector3 — MUST be normalized, default: (0, 0, -1)
  near,       // number — minimum distance, default: 0
  far         // number — maximum distance, default: Infinity
);

Properties

PropertyTypeDefaultDescription
rayRay--Underlying Ray object (origin + direction)
nearnumber0Minimum intersection distance
farnumberInfinityMaximum intersection distance
cameraCamera--Required for raycasting against Sprite objects
layersLayerslayer 0Layer mask -- only objects on matching layers are tested
paramsobjectsee belowPer-type intersection thresholds

Params Defaults

javascript
raycaster.params = {
  Mesh: {},
  Line: { threshold: 1 },    // world units distance for line hits
  LOD: {},
  Points: { threshold: 1 },  // world units distance for point hits
  Sprite: {}
};

Critical Warnings

NEVER raycast on every mousemove event without throttling -- this causes severe frame drops on complex scenes. ALWAYS throttle to the render loop via requestAnimationFrame or limit to 30-60 checks per second.

NEVER pass recursive: true on large scene graphs when you have a flat array of target objects -- ALWAYS maintain a flat array of selectable objects and pass recursive: false to avoid unnecessary tree traversal.

NEVER forget to normalize the direction vector when using raycaster.set() -- an unnormalized direction produces incorrect distance values in all intersection results.

NEVER allocate a new results array every frame -- ALWAYS reuse an array via the optionalTarget parameter and clear it with array.length = 0 after processing.

NEVER raycast against the entire scene.children when only a subset of objects is interactive -- ALWAYS maintain a separate array of selectable objects or use layers for filtering.

NEVER omit raycaster.camera when raycasting against Sprite objects -- the raycaster requires the camera reference to compute sprite screen-space bounds.


Core Methods

set(origin, direction)

Manually sets the ray origin and direction. Direction MUST be normalized.

javascript
const origin = new THREE.Vector3(0, 1, 0);
const direction = new THREE.Vector3(0, -1, 0); // already normalized
raycaster.set(origin, direction);

setFromCamera(coords, camera)

Sets the ray from normalized device coordinates (NDC) and a camera. This is the standard mouse-picking method.

  • coords: Vector2 with x and y in range [-1, +1]
  • camera: PerspectiveCamera produces a ray from the camera through the point; OrthographicCamera produces a parallel ray
javascript
const mouse = new THREE.Vector2();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);

intersectObject(object, recursive?, optionalTarget?)

Tests a single object (and optionally its descendants) for intersections.

  • recursive (default: true): when true, tests all descendants
  • optionalTarget: reusable array to avoid allocation
  • Returns: Intersection[] ALWAYS sorted by distance (nearest first)

intersectObjects(objects, recursive?, optionalTarget?)

Tests an array of objects for intersections.

  • recursive (default: true): when true, tests descendants of each object
  • optionalTarget: reusable array to avoid allocation
  • Returns: Intersection[] ALWAYS sorted by distance (nearest first)

Intersection Object Format

Every intersection in the returned array has this structure:

typescript
interface Intersection {
  distance: number;       // distance from ray origin to hit point
  point: Vector3;         // hit point in world space
  face: Face | null;      // hit face ({a, b, c} vertex indices + normal)
  faceIndex: number;      // index of hit face in the geometry
  object: Object3D;       // the intersected object reference
  uv?: Vector2;           // UV coordinates at intersection point
  uv1?: Vector2;          // second UV set (if available)
  normal?: Vector3;       // interpolated surface normal at hit point
  instanceId?: number;    // instance index (only for InstancedMesh)
}

ALWAYS check intersects.length > 0 before accessing intersects[0]. The array is empty when no objects are hit.


NDC Conversion (Normalized Device Coordinates)

Converting DOM mouse coordinates to NDC is required for setFromCamera. The NDC space ranges from -1 (left/bottom) to +1 (right/top).

javascript
// For fullscreen canvas (canvas fills entire window)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

// For non-fullscreen canvas (canvas has offset within page)
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

ALWAYS use getBoundingClientRect() when the canvas does NOT fill the entire viewport. Using window.innerWidth/Height on a partial canvas produces incorrect NDC values and misaligned picking.


InstancedMesh Picking

When raycasting against InstancedMesh, the intersection result includes instanceId identifying which instance was hit:

javascript
import * as THREE from 'three';

const intersects = raycaster.intersectObject(instancedMesh);
if (intersects.length > 0) {
  const instanceId = intersects[0].instanceId;
  // Retrieve the instance's transform matrix
  const matrix = new THREE.Matrix4();
  instancedMesh.getMatrixAt(instanceId, matrix);

  // Example: change the color of the hit instance
  const color = new THREE.Color();
  instancedMesh.getColorAt(instanceId, color);
  instancedMesh.setColorAt(instanceId, new THREE.Color(0xff0000));
  instancedMesh.instanceColor.needsUpdate = true;
}

ALWAYS check that instanceId !== undefined before using it -- non-InstancedMesh objects do not have this property.


Layer Filtering

Raycaster respects the Layers system. Only objects whose layers overlap with raycaster.layers are tested.

javascript
// Assign objects to layers
selectableMesh.layers.set(1);        // exclusively on layer 1
decorationMesh.layers.set(2);        // exclusively on layer 2

// Configure raycaster to only test layer 1
raycaster.layers.set(1);
// Now intersectObjects skips all objects NOT on layer 1

// Enable multiple layers
raycaster.layers.enable(1);
raycaster.layers.enable(2);
// Now tests objects on layer 1 OR layer 2

// Reset to default (layer 0 only)
raycaster.layers.set(0);

Use layers to create picking groups: interactive objects on layer 1, non-interactive decoration on layer 2, helpers/gizmos on layer 3.


Performance Guidelines

  1. Throttle mousemove raycasting -- NEVER raycast on every mousemove event. Use a flag checked in the render loop:

    javascript
    let needsRaycast = false;
    canvas.addEventListener('pointermove', (event) => {
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
      needsRaycast = true;
    });
    
    function animate() {
      if (needsRaycast) {
        raycaster.setFromCamera(mouse, camera);
        // perform intersection tests
        needsRaycast = false;
      }
      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }
  2. Use layers -- assign interactive objects to a specific layer and set raycaster.layers accordingly to skip non-interactive geometry entirely.

  3. Maintain a flat selectable array -- instead of raycasting against scene with recursive: true, keep a separate selectableObjects[] array and pass recursive: false.

  4. Reuse the intersections array -- pass optionalTarget to avoid garbage collection:

    javascript
    const intersections = [];
    raycaster.intersectObjects(selectableObjects, false, intersections);
    // process results...
    intersections.length = 0;
  5. Bounding sphere pre-check -- Three.js automatically tests bounding spheres before triangle intersection. Ensure geometry.computeBoundingSphere() has been called (it is called automatically on first render, but manual call is needed if raycasting before first render).

  6. Limit near/far -- narrow the ray range when you know the expected intersection distance to skip distant objects early.


Reference Links

Official Sources

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA Threejs Core Raycaster?

Use when implementing mouse picking, hover detection, object selection, or line-of-sight checks in Three.js. Prevents the common mistake of raycasting every mousemove frame, not using layers for filtering, or missing recursive flag. Covers Raycaster, setFromCamera, intersection format, InstancedMesh picking, layers, performance. Keywords: Raycaster, mouse picking, intersectObjects, click, hover, setFromCamera, intersection, instanceId, object selection, click on 3D object, detect mouse over, pick element.

Perché usare Threejs Core Raycaster su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Threejs Core Raycaster è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Threejs Core Raycaster in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package/tree/master/skills/source/threejs-core/threejs-core-raycaster. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Threejs Core Raycaster?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Threejs Core Raycaster?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Threejs Core Raycaster: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Threejs Core Raycaster è gratuita?

Sì. È pubblicata su GitHub da Impertio-Studio con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇