Логотип Unity Physics Queries

Unity Physics Queries

Организация
Nice-Wolf-Studio
unity-physics-queries

Unity physics query correctness patterns. Catches common mistakes with Raycast, SphereCast, OverlapSphere, NonAlloc allocation, LayerMask construction, trigger interaction, hit ordering, and query type selection. PATTERN format: WHEN/WRONG/RIGHT/GOTCHA. Based on Unity 6.3 LTS.

Обзор

ИздательNice-Wolf-Studio
Репозиторийunity-claude-skills
Название навыкаunity-physics-queries
Звёзды
40
Форки
5
Встроенные файлы
1
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 1

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Опубликовано на GitHub: Nice-Wolf-Studio. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Unity Physics Queries в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-physics-queries
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nice-Wolf-Studio/unity-claude-skills.git /tmp/unity-claude-skills
mkdir -p .claude/skills
cp -r /tmp/unity-claude-skills/skills/unity-physics-queries .claude/skills/unity-physics-queries
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Unity Physics Queries в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Unity Physics Queries, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Unity Physics Queries не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Physics Query Patterns -- Correctness Patterns

Prerequisite skills: unity-physics (Rigidbody, colliders, raycasting API), unity-foundations (layers, GameObjects)

These patterns target the most common physics query bugs: using the wrong query type, misunderstanding allocation, and ignoring subtle defaults that cause silent failures.


PATTERN: Query Type Selection

WHEN: Choosing which physics query to use

WRONG (Claude default):

csharp
// Always defaulting to Raycast for everything
Physics.Raycast(origin, direction, out hit, maxDistance);

RIGHT -- use the decision tree:

Need to detect...
  |
  +-- "Is anything there?" (binary yes/no)
  |     --> CheckSphere, CheckBox, CheckCapsule (returns bool, cheapest)
  |
  +-- "What's the nearest thing along a line?"
  |     --> Raycast (single closest hit along an infinitely thin line)
  |
  +-- "What's the nearest thing along a volume?"
  |     --> SphereCast, BoxCast, CapsuleCast (sweep a shape, single closest hit)
  |
  +-- "Everything along a line?"
  |     --> RaycastAll / RaycastNonAlloc (all hits, not just closest)
  |
  +-- "Everything inside an area?"
        --> OverlapSphere, OverlapBox, OverlapCapsule (all colliders in region)

GOTCHA: Raycast only returns the closest hit. If you need to pierce through multiple objects, use RaycastAll or RaycastNonAlloc. If you need to detect everything in an area (like an explosion radius), OverlapSphere is correct -- NOT SphereCast.


PATTERN: Cast Origin Inside Collider

WHEN: A SphereCast/BoxCast/CapsuleCast starts overlapping an existing collider

WRONG (Claude default):

csharp
// Expecting to detect the ground when the sphere starts inside it
if (Physics.SphereCast(feetPosition, radius, Vector3.down, out hit, 0.1f))
{
    grounded = true; // May MISS if sphere starts inside the ground collider
}

RIGHT:

csharp
// Casts do NOT detect colliders that the shape starts inside of
// Use Overlap for "what am I currently touching?"
grounded = Physics.CheckSphere(feetPosition, radius, groundMask);

// Or use OverlapSphere to get the actual colliders:
Collider[] touching = Physics.OverlapSphere(feetPosition, radius, groundMask);

GOTCHA: This applies to ALL cast queries (SphereCast, BoxCast, CapsuleCast, Raycast). If the origin is inside a collider, that collider is ignored. This is the #1 source of "my ground check doesn't work" bugs. Raycasts that start inside a MeshCollider also miss it. Use Overlap* or Check* for current-overlap detection.


PATTERN: Hit Ordering Not Guaranteed

WHEN: Using RaycastAll or RaycastNonAlloc and expecting sorted results

WRONG (Claude default):

csharp
RaycastHit[] hits = Physics.RaycastAll(origin, direction, maxDist);
// Assuming hits[0] is the closest
ProcessHit(hits[0]);

RIGHT:

csharp
RaycastHit[] hits = Physics.RaycastAll(origin, direction, maxDist);
// Results are NOT sorted by distance -- sort manually
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
if (hits.Length > 0)
    ProcessHit(hits[0]); // Now this is the closest

GOTCHA: Regular Physics.Raycast (single hit) always returns the closest. Only RaycastAll and RaycastNonAlloc return unsorted results. The same applies to SphereCastAll/SphereCastNonAlloc, etc. For NonAlloc, sort only up to the returned count, not the full buffer.


PATTERN: NonAlloc Buffer Size and Return Count

WHEN: Using RaycastNonAlloc, OverlapSphereNonAlloc, or similar zero-allocation queries

WRONG (Claude default):

csharp
// Buffer of 1 -- silently drops extra results
RaycastHit[] buffer = new RaycastHit[1];
int count = Physics.RaycastNonAlloc(ray, buffer, maxDist);

RIGHT:

csharp
// Pre-allocate a reasonably sized buffer as a class field
private readonly RaycastHit[] _hitBuffer = new RaycastHit[16];

void DetectHits()
{
    int count = Physics.RaycastNonAlloc(ray, _hitBuffer, maxDist, layerMask);

    // ONLY iterate up to count, not buffer.Length
    for (int i = 0; i < count; i++)
    {
        ProcessHit(_hitBuffer[i]);
    }

    // If count == buffer.Length, you may have missed results
    if (count == _hitBuffer.Length)
        Debug.LogWarning("Hit buffer full -- may have missed results");
}

GOTCHA: NonAlloc fills the provided buffer and returns how many results were written. If there are more results than buffer capacity, extras are silently dropped with no error. Size your buffer to the maximum expected results for your use case. Common sizes: ground check = 4, explosion radius = 32, broad scan = 64.


PATTERN: LayerMask Bitshift vs GetMask

WHEN: Constructing a layer mask for physics queries

WRONG (Claude default):

csharp
// DOUBLE-SHIFTING: GetMask already returns a bitmask, not a layer index
int mask = 1 << LayerMask.GetMask("Ground"); // WRONG -- shifts a bitmask by a bitmask amount

RIGHT:

csharp
// GetMask returns the final bitmask -- use directly
int groundMask = LayerMask.GetMask("Ground");
int multiMask = LayerMask.GetMask("Ground", "Water", "Default");

// NameToLayer returns the layer INDEX -- this one needs the shift
int groundLayer = LayerMask.NameToLayer("Ground"); // Returns e.g. 8
int groundMask2 = 1 << groundLayer;                // Correct: 1 << 8 = 256

// Combining with bitwise OR
int combinedMask = (1 << LayerMask.NameToLayer("Ground")) | (1 << LayerMask.NameToLayer("Water"));

// Inverting a mask (everything EXCEPT these layers)
int everythingButGround = ~LayerMask.GetMask("Ground");

GOTCHA: LayerMask.GetMask("Ground") = bitmask (e.g., 256). LayerMask.NameToLayer("Ground") = index (e.g., 8). gameObject.layer = index. Passing a layer index where a mask is expected (or vice versa) silently filters wrong layers with no error.


PATTERN: QueryTriggerInteraction Default

WHEN: Raycasts or other queries are unexpectedly hitting trigger colliders

WRONG (Claude default):

csharp
// Assuming triggers are ignored by queries
if (Physics.Raycast(origin, direction, out hit, maxDist, layerMask))
{
    // hit.collider might be a trigger!
}

RIGHT:

csharp
// Explicitly control trigger interaction
if (Physics.Raycast(origin, direction, out hit, maxDist, layerMask, QueryTriggerInteraction.Ignore))
{
    // Guaranteed to only hit non-trigger colliders
}

// Or check at the hit level
if (Physics.Raycast(origin, direction, out hit, maxDist, layerMask))
{
    if (!hit.collider.isTrigger)
    {
        // Process only non-trigger hits
    }
}

GOTCHA: The default is QueryTriggerInteraction.UseGlobal, which reads from Physics.queriesHitTriggers. That global default is true -- meaning queries DO hit triggers by default. This catches many developers off guard. Set it explicitly when trigger hits would cause bugs (ground checks, line-of-sight, bullet traces).


PATTERN: SphereCast Radius vs Distance

WHEN: Using SphereCast and confusing the parameters

WRONG (Claude default):

csharp
// Confusing parameters: treating radius as detection range
Physics.SphereCast(origin, detectionRange, direction, out hit);
// This creates a sphere with radius=detectionRange that travels infinitely far

RIGHT:

csharp
// radius = SIZE of the sphere being swept
// maxDistance = how FAR the sphere travels
float sphereRadius = 0.5f;
float castDistance = 10f;
if (Physics.SphereCast(origin, sphereRadius, direction, out hit, castDistance, layerMask))
{
    // hit.distance = distance the sphere CENTER traveled, not the surface
    // hit.point = point on the surface of the OTHER collider (not the sphere)
}

GOTCHA: hit.distance is the distance the sphere's center traveled before contact, NOT the total distance from origin to the hit surface. The actual contact surface is at hit.point. A SphereCast with radius=0 behaves like a Raycast. If the sphere is very large and the cast distance is short, you may miss nearby objects due to the "origin inside collider" issue.


PATTERN: CapsuleCast Point Parameters

WHEN: Setting up CapsuleCast endpoints

WRONG (Claude default):

csharp
// Using center + full height
Physics.CapsuleCast(center, center + Vector3.up * height, radius, direction, out hit);

RIGHT:

csharp
// point1 and point2 are the centers of the two HEMISPHERES (not the full endpoints)
// For a character with height 2.0 and radius 0.5:
float height = 2.0f;
float radius = 0.5f;
Vector3 point1 = center + Vector3.up * (height * 0.5f - radius); // Top hemisphere center
Vector3 point2 = center - Vector3.up * (height * 0.5f - radius); // Bottom hemisphere center
Physics.CapsuleCast(point1, point2, radius, direction, out hit, maxDistance, layerMask);

GOTCHA: The total capsule height = |point2 - point1| + 2 * radius. If point1 == point2, it degenerates into a SphereCast. The CapsuleCollider component defines this differently (center + height + radius), so translating from a CapsuleCollider requires: point1 = center + up * (height/2 - radius), point2 = center - up * (height/2 - radius).


PATTERN: Backface Detection

WHEN: Raycasting against MeshColliders from behind

WRONG (Claude default):

csharp
// Assuming raycasts hit both sides of a mesh triangle
if (Physics.Raycast(insidePoint, direction, out hit))
{
    // May not hit if ray goes through backface of MeshCollider
}

RIGHT:

csharp
// Enable backface hits globally (affects all queries)
Physics.queriesHitBackfaces = true;

// Or design around it:
// Convex MeshColliders are always hit from both sides
// Primitive colliders (Box, Sphere, Capsule) are always hit from both sides
// Only non-convex MeshColliders have single-sided detection by default

GOTCHA: By default, Physics.queriesHitBackfaces = false. This only affects non-convex MeshColliders. Box, Sphere, Capsule, and convex MeshColliders detect hits from any direction. If you need to raycast from inside a non-convex mesh (e.g., room interior), either enable backface queries or use a convex collider for the interior.


PATTERN: Scene-Specific Queries

WHEN: Using additive scenes with separate physics simulations

WRONG (Claude default):

csharp
// Global queries search ALL physics scenes
Collider[] results = Physics.OverlapSphere(center, radius);

RIGHT:

csharp
// Get the physics scene for a specific Unity scene
PhysicsScene physScene = gameObject.scene.GetPhysicsScene();

// Query only within that physics scene
RaycastHit hit;
if (physScene.Raycast(origin, direction, out hit, maxDist, layerMask))
{
    // Only hits colliders in this physics scene
}

// OverlapSphere with scene scope
Collider[] buffer = new Collider[32];
int count = physScene.OverlapSphere(center, radius, buffer, layerMask);

GOTCHA: By default, all scenes share the same Physics.defaultPhysicsScene. Scene-specific physics only matters when you explicitly create scenes with LocalPhysicsMode.Physics3D. Most projects never need this -- but it's critical for multiplayer prediction, parallel simulations, or editor preview scenes.


Anti-Patterns Quick Reference

Anti-PatternProblemFix
Physics.Raycast in Update without layer maskHits everything including UI collidersAlways pass a LayerMask parameter
Allocating new RaycastHit[] every frameGC pressureUse NonAlloc with a cached buffer
OverlapSphere with radius 0Returns nothingRadius must be > 0; use CheckSphere for point checks
Comparing hit.distance across different query typesSphereCast distance != Raycast distanceSphereCast distance is center travel, not surface distance
Using maxDistance = Mathf.InfinityQueries entire scene, expensiveUse a reasonable max distance for your use case
Forgetting QueryTriggerInteraction.Ignore on ground checksTrigger volumes falsely report "grounded"Pass QueryTriggerInteraction.Ignore explicitly

Related Skills

  • unity-physics -- Rigidbody, colliders, collision/trigger events, physics settings API
  • unity-3d-math -- Raycasting projection, Plane math, coordinate spaces
  • unity-performance -- Profiling physics queries, optimization patterns

Additional Resources

Встроенные файлы

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Unity Physics Queries?

Unity physics query correctness patterns. Catches common mistakes with Raycast, SphereCast, OverlapSphere, NonAlloc allocation, LayerMask construction, trigger interaction, hit ordering, and query type selection. PATTERN format: WHEN/WRONG/RIGHT/GOTCHA. Based on Unity 6.3 LTS.

Зачем использовать Unity Physics Queries в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Unity Physics Queries — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Unity Physics Queries в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-physics-queries. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Unity Physics Queries?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Unity Physics Queries?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Unity Physics Queries: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Unity Physics Queries?

Да. Навык опубликован на GitHub автором Nice-Wolf-Studio по лицензии MIT. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇