AGENT SKILL

wave5-physics-world-singleton-queries

Perform runtime spatial queries (raycast, collider cast, distance, overlap) against the Unity Physics collision world using PhysicsWorldSingleton.

License 许可
MIT
最近更新
2026-07-25
Stars
★ 8
Forks
0

01 前言 Front Matter

name
wave5-physics-world-singleton-queries
tags
[ "physics", "query", "singleton" ]
metadata
{ "tier": 3, "internal-only": true }
description
Perform runtime spatial queries (raycast, collider cast, distance, overlap) against the Unity Physics collision world using PhysicsWorldSingleton.

03 SKILL.md 正文

PhysicsWorldSingleton Spatial Queries

Intent

Perform runtime spatial queries (raycast, collider cast, distance, overlap) against the Unity Physics collision world using PhysicsWorldSingleton.

Use When

  • Line-of-sight checks, ground detection, projectile trajectory, AOE range detection
  • Spatial queries against current physics world state (after world build)

Avoid When

  • Queries inside FixedStepSimulationSystemGroup before PhysicsBuildWorldGroup — world not yet built
  • Per-entity collision response — use trigger/collision event buffers instead

Senior Pattern

[UpdateInGroup(typeof(SimulationSystemGroup))]
[BurstCompile]
public partial struct RaycastSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        // Complete physics jobs before reading PhysicsWorldSingleton:
        state.EntityManager.CompleteDependencyBeforeRO<PhysicsWorldSingleton>();

        var physicsWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>().PhysicsWorld;

        state.Dependency = new RaycastJob
        {
            World = physicsWorld.CollisionWorld,
            Input = new RaycastInput
            {
                Start = float3.zero,       // replace with actual origin
                End = float3.zero + math.forward() * 100f,
                Filter = new CollisionFilter
                {
                    BelongsTo = ~0u,
                    CollidesWith = 1u << 0,  // target layer only
                    GroupIndex = 0
                }
            },
            Hits = new NativeList<RaycastHit>(Allocator.TempJob)
        }.Schedule(state.Dependency);
    }
}

[BurstCompile]
public struct RaycastJob : IJob
{
    [ReadOnly] public CollisionWorld World;
    public RaycastInput Input;
    public NativeList<RaycastHit> Hits;

    public void Execute() { World.CastRay(Input, ref Hits); }
}

Available query types:

// Single closest hit:
world.CollisionWorld.CastRay(input, out RaycastHit hit)

// All hits:
world.CollisionWorld.CastRay(input, ref NativeList<RaycastHit> hits)

// Shape cast:
world.CollisionWorld.CastCollider(input, out ColliderCastHit hit)

// Nearest body to point:
world.CollisionWorld.CalculateDistance(input, out DistanceHit hit)

// Broad-phase AABB overlap:
world.CollisionWorld.OverlapAabb(input, ref NativeList<int> bodyIndices)

Anti-Patterns

  • Forgetting CompleteDependencyBeforeRO<PhysicsWorldSingleton>() — physics jobs may still be writing; safety error or silent corruption.
  • Using CollisionFilter.Default for all queries — hits every body; expensive in dense scenes.
  • Scheduling per-entity parallel raycasts via ScheduleParallel — CollisionWorld is shared read-only; batch into a single IJob.Schedule instead.
  • Querying inside FixedStepSimulationSystemGroup [UpdateBefore(PhysicsSystemGroup)] — world not yet built for this tick.

Runtime Risks

  • PhysicsWorldSingleton is valid only after PhysicsBuildWorldGroup completes — in SimulationSystemGroup it is always valid (physics runs in fixed step before simulation group).
  • ColliderCastInput contains an unsafe Collider pointer — requires [NativeDisableUnsafePtrRestriction] on the field in a job struct.
  • NativeList<RaycastHit> allocated with Allocator.TempJob must be Disposed within 4 frames — or use WorldUpdateAllocator.

Performance Notes

  • Single raycast against well-built BVH: O(log N) — very fast.
  • Always use CollisionFilter to reduce candidates; batch multiple raycasts into one IJob.
  • For many queries per frame, pre-build a NativeArray<RaycastInput> and process all in one IJobParallelFor.

Architecture Guidance

  • Place query systems in SimulationSystemGroup [UpdateAfter(TransformSystemGroup)] for up-to-date positions.
  • Always narrow CollisionFilter to minimum necessary layers — review with collision-filter-layer-masking skill.
  • Do not store PhysicsWorld reference across frames — rebuild from PhysicsWorldSingleton each OnUpdate.

Related Skills

[[wave5-fixed-step-simulation-system-group]], [[wave5-collision-filter-layer-masking]], [[wave5-physics-velocity-force-application]], [[wave4-world-update-allocator-per-frame-native]]

04 同仓库更多 Skills

dyCuong03
dyCuong03/unity-agent-team

dots-update-groups

How to choose the right ECS system group and ordering so per-frame and per-fixed-step work is deterministic and never races its own readers. Covers InitializationSystemGroup / SimulationSystemGroup / PresentationSystemGroup / FixedStepSimulationSystemGroup / VariableRateSimulationSystemGroup, UpdateBefore / UpdateAfter peer ordering, OrderFirst / OrderLast group-boundary placement, RateManager, and the cross-group ordering trap. Use when adding an ISystem, fixing "value visible one frame late" bugs, or coupling simulation to a fixed timestep.

★ 8
dyCuong03
dyCuong03/unity-agent-team

dots-transform-patterns

The Entities 1.x transform model — LocalTransform (writable input) vs LocalToWorld (system-owned matrix), Parent/Child hierarchy, reparenting cost, uniform vs non-uniform scale (PostTransformMatrix), and when to opt out with custom transform systems. Use when designing parent/child hierarchies, runtime reparenting (mount/dismount/socket), or choosing transform components at the Baker boundary.

★ 8
dyCuong03
dyCuong03/unity-agent-team

dots-singleton-patterns

Model cross-system shared configuration and game state as a single-entity component with a strict single-writer contract. Covers RequireForUpdate gating, SystemAPI.GetSingleton / GetSingletonRW / HasSingleton / TryGetSingleton, bake-time vs runtime-created vs ECB-system singletons, the "exactly one entity" runtime invariant, and the single-writer rule. Use when designing frame-stable global config, shared mutable state, or any component intended to exist on exactly one entity.

律师与法务
★ 8
dyCuong03
dyCuong03/unity-agent-team

dots-hybrid-bridge

The one-way bridge between DOTS-owned runtime state and Unity-owned presentation. Covers UnityObjectRef for managed asset refs in components, the DOTS-writes / Unity-reads ownership rule, when to use managed IComponentData vs UnityObjectRef vs CompanionComponent, baker-bridge vs runtime-bridge, and SubScene boundary rules. Use when an entity must reference Unity assets (Mesh, Material, AudioClip, ScriptableObject), a MonoBehaviour view must read entity state, or input/UI must trigger ECS work.

★ 8
dyCuong03
dyCuong03/unity-agent-team

dots-event-driven-ecs

Model one-frame events and external requests in ECS without dual ownership, polling, or persistent state leaks. Covers request-tag pattern with ECB, enableable command components (no structural change), event buffers (IBufferElementData), explicit consumer ownership, one-frame latency rules, and the banned C# event / UnityEvent / static bus anti-patterns. Use when input/UI/network must trigger ECS work, when a one-frame signal fans out to N consumers (damage, hit, collision), or when state changes must be processed exactly once.

★ 8
dyCuong03
dyCuong03/unity-agent-team

valid_skill

A complete, well-formed test fixture skill for SkillHub validation testing. Covers basic task routing and code review for Unity projects.

代码审查测试与质量
★ 8