### Raycast example using PhysicsWorldSingleton Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/collision-queries.html This example shows how to perform a ray cast using the PhysicsWorldSingleton. It sets up an EntityQuery to get the CollisionWorld, creates a RaycastInput with a filter that collides with all layers, and returns the closest hit Entity or Entity.Null if no hit. The code includes comments about using GetSingleton in SystemBase or ISystem. ```csharp public Entity Raycast(float3 RayFrom, float3 RayTo) { // Set up Entity Query to get PhysicsWorldSingleton // If doing this in SystemBase or ISystem, call GetSingleton()/SystemAPI.GetSingleton() directly. EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.Temp).WithAll(); EntityQuery singletonQuery = World.DefaultGameObjectInjectionWorld.EntityManager.CreateEntityQuery(builder); var collisionWorld = singletonQuery.GetSingleton().CollisionWorld; singletonQuery.Dispose(); RaycastInput input = new RaycastInput() { Start = RayFrom, End = RayTo, Filter = new CollisionFilter() { BelongsTo = ~0u, CollidesWith = ~0u, // all 1s, so all layers, collide with everything GroupIndex = 0 } }; RaycastHit hit = new RaycastHit(); bool haveHit = collisionWorld.CastRay(input, out hit); if (haveHit) { return hit.Entity; } return Entity.Null; } ``` -------------------------------- ### Collider cast (sphere) example using PhysicsWorldSingleton Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/collision-queries.html This example shows how to perform a collider cast (specifically a sphere cast) using the PhysicsWorldSingleton. It sets up an EntityQuery to get the CollisionWorld, creates a sphere collider, and performs a ColliderCast. It returns the closest hit Entity or Entity.Null if no hit. The code includes comments about using GetSingleton in SystemBase or ISystem. ```csharp public unsafe Entity SphereCast(float3 RayFrom, float3 RayTo, float radius) { // Set up Entity Query to get PhysicsWorldSingleton // If doing this in SystemBase or ISystem, call GetSingleton()/SystemAPI.GetSingleton() directly. EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.Temp).WithAll(); EntityQuery singletonQuery = World.DefaultGameObjectInjectionWorld.EntityManager.CreateEntityQuery(builder); var collisionWorld = singletonQuery.GetSingleton().CollisionWorld; singletonQuery.Dispose(); var filter = new CollisionFilter() { BelongsTo = ~0u, CollidesWith = ~0u, // all 1s, so all layers, collide with everything GroupIndex = 0 }; SphereGeometry sphereGeometry = new SphereGeometry() { Center = float3.zero, Radius = radius }; BlobAssetReference sphereCollider = SphereCollider.Create(sphereGeometry, filter); ColliderCastInput input = new ColliderCastInput() { Collider = (Collider*)sphereCollider.GetUnsafePtr(), Orientation = quaternion.identity, Start = RayFrom, End = RayTo }; ColliderCastHit hit = new ColliderCastHit(); bool haveHit = collisionWorld.CastCollider(input, out hit); if (haveHit) { return hit.Entity; } sphereCollider.Dispose(); return Entity.Null; } ``` -------------------------------- ### Create Position Motor with C# API Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/custom-motors.html Use this API call to create a Position Motor. The parameters include body frames, target position, max impulse, spring frequency, and damping ratio. Ensure all axes in BodyFrame are normalized. The example settings correspond to General Position Motor Example 1. ```csharp PhysicsJoint.CreatePositionMotor( bodyAFromJoint, bodyBFromJoint, target, maxImpulseOfMotor, springFrequency, dampingRatio) ``` -------------------------------- ### Create Dynamic Sphere and Body with Physics Components Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/create-body.html This snippet shows how to create a dynamic sphere collider and a generic body creation method that sets up physics components (PhysicsCollider, PhysicsVelocity, PhysicsMass, etc.) and rendering for an entity. It includes commented-out code for alternative PhysicsMass setup and uses RenderMeshUtility.AddComponents for rendering. ```csharp Enabled = false; } private Entity CreateDynamicSphere(EntityManager entityManager, RenderMeshArray renderMeshArray, MaterialMeshInfo materialMeshInfo, RenderMeshDescription renderMeshDescription, int uniformScale, float radius, float3 position, quaternion orientation) { SphereGeometry sphereGeometry = new SphereGeometry { Center = float3.zero, Radius = radius }; // Sphere with default filter and material. Add to Create() call if you want non default: BlobAssetReference sphereCollider = Unity.Physics.SphereCollider.Create(sphereGeometry, CollisionFilter.Default); return CreateBody(entityManager, renderMeshArray, materialMeshInfo, renderMeshDescription, position, orientation, uniformScale, sphereCollider, float3.zero, float3.zero, 1.0f, true); } private unsafe Entity CreateBody(EntityManager entityManager, RenderMeshArray renderMeshArray, MaterialMeshInfo materialMeshInfo, RenderMeshDescription renderMeshDescription, float3 position, quaternion orientation, float uniformScale, BlobAssetReference collider, float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic) { ComponentType[] componentTypes = new ComponentType[isDynamic ? 8 : 4]; componentTypes[0] = typeof(LocalTransform); componentTypes[1] = typeof(LocalToWorld); componentTypes[2] = typeof(PhysicsCollider); componentTypes[3] = typeof(PhysicsWorldIndex); if (isDynamic) { componentTypes[4] = typeof(PhysicsVelocity); componentTypes[5] = typeof(PhysicsMass); componentTypes[6] = typeof(PhysicsDamping); componentTypes[7] = typeof(PhysicsGravityFactor); } Entity entity = entityManager.CreateEntity(componentTypes); RenderMeshUtility.AddComponents(entity, entityManager, renderMeshDescription, renderMeshArray, materialMeshInfo); entityManager.SetComponentData(entity, new RenderBounds { Value = new AABB { Center = new float3(0, 0, 0), Extents = new float3(0.5f, 0.5f, 0.5f) } }); entityManager.SetComponentData(entity, new LocalTransform { Position = position, Rotation = orientation, Scale = uniformScale }); if (uniformScale != 1.0f) { entityManager.AddComponentData(entity, new PostTransformScale { Value = new float3x3 { c0 = new float3(1, 1, 1) * uniformScale, c1 = new float3(1, 1, 1) * uniformScale, c2 = new float3(1, 1, 1) * uniformScale } }); } entityManager.SetComponentData(entity, new PhysicsCollider { Value = collider }); //By default Physics simulation happens in PhysicsWorldIndex 0. EntityManager.AddSharedComponentManaged(entity, new PhysicsWorldIndex { Value = 0 }); if (!isDynamic) return entity; Collider* colliderPtr = (Collider*)collider.GetUnsafePtr(); entityManager.SetComponentData(entity, PhysicsMass.CreateDynamic(colliderPtr->MassProperties, mass)); /*entityManager.SetComponentData(entity, new PhysicsMass { Transform = new RigidTransform { pos = new float3(0, 0, 0), rot = quaternion.identity }, InverseMass = 1, InverseInertia = new float3(10, 10, 10), AngularExpansionFactor = 0 });*/ // Calculate the angular velocity in local space from rotation and world angular velocity float3 angularVelocityLocal = math.mul(math.inverse(colliderPtr->MassProperties.MassDistribution.Transform.rot), angularVelocity); entityManager.SetComponentData(entity, new PhysicsVelocity() { Linear = linearVelocity, Angular = angularVelocityLocal }); entityManager.SetComponentData(entity, new PhysicsDamping() { Linear = 0.01f, Angular = 0.05f }); entityManager.SetComponentData(entity, new PhysicsGravityFactor { Value = 1 }); return entity; } } ``` -------------------------------- ### CustomPhysicsSystemGroup example with world index check Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/group-body.html Defines a custom physics system group that simulates entities with world index 1 and shares static entities with the main world. The CheckWorldIndexSystem runs inside both the main physics group and the custom group, using PhysicsWorldIndex to branch behavior. ```csharp [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] public partial class UserPhysicsGroup : CustomPhysicsSystemGroup { public UserPhysicsGroup() : base(1, true) {} // our physics group will simulate entities with world index 1, and share static entities with main world } [UpdateInGroup(PhysicsInitializeGroup)] // As the system updates inside [PhysicsSinitializeGroup], it will automatically be ran inside UserPhysicsGroup as well public partial class CheckWorldIndexSystem : SystemBase { protected override void OnUpdate() { var physicsWorldSingleton = GetSingleton(); if (physicsWorldSingleton.PhysicsWorldIndex.Value == 0) { // ... // When ran as part of main physics group, this code path will be hit. } else { // ... // When ran as part of UserPhysicsGroup, this code path will be hit. } } } ``` -------------------------------- ### PhysicsWorldSingleton usage example (ISystem and SystemBase versions) Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/physics-singletons.html Shows how to retrieve and use PhysicsWorldSingleton in both ISystem and SystemBase systems. The ISystem version schedules a CastRay job and also demonstrates main-thread access and direct PhysicsWorld access. The SystemBase version defines a CastRayJob that takes the singleton as a field and schedules it, with a main-thread fallback. Both versions require correct system update ordering via UpdateBefore. ```csharp // ISystem version [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] [UpdateBefore(typeof(PhysicsSystemGroup))] // Make sure that the running order of systems is correct public partial struct CastRayISystemExample : ISystem { [BurstCompile] public partial struct CastRayJob : IJob { public PhysicsWorldSingleton World; public void Execute() { World.CastRay(...); } } [BurstCompile] public void OnUpdate(ref SystemState state) { PhysicsWorldSingleton physicsWorldSingleton = SystemAPI.GetSingleton(); // Version that schedules a job state.Dependency = new CastRayJob { World = physicsWorldSingleton }.Schedule(state.Dependency); // Main thread version - be sure to complete the dependency state.CompleteDependency(); physicsWorldSingleton.CastRay(...); // It is also possible to access the PhysicsWorld PhysicsWorld world = physicsWorldSingleton.PhysicsWorld; } } ``` ```csharp // SystemBase version [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] [UpdateBefore(typeof(PhysicsSystemGroup))] // Make sure that the running order of systems is correct public partial class CastRaySystemBaseExample : SystemBase { public partial struct CastRayJob : IJob { public PhysicsWorldSingleton World; [BurstCompile] public void Execute() { World.CastRay(...); } } protected override void OnUpdate() { PhysicsWorldSingleton physicsWorldSingleton = GetSingleton(); // Version that schedules a job state.Dependency = new CastRayJob { World = physicsWorldSingleton }.Schedule(state.Dependency); // Main thread version - be sure to complete the dependency CompleteDependency(); physicsWorldSingleton.CastRay(...); // It is also possible to access the PhysicsWorld PhysicsWorld world = physicsWorldSingleton.PhysicsWorld; } } ``` -------------------------------- ### Config, ConfigAuthoring, ConfigBaker, and SphereSpawningSystem for spawning prefabs Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/create-body.html Defines the Config component, ConfigAuthoring MonoBehaviour, ConfigBaker, and SphereSpawningSystem to spawn a prefab multiple times at runtime. The system uses BeginSimulationEntityCommandBufferSystem to instantiate entities and sets their LocalTransform. It disables itself after one update. ```C# using UnityEngine; using Unity.Entities; using Unity.Burst; using Unity.Mathematics; using Unity.Transforms; public struct Config : IComponentData { public Entity SpherePrefab; public int SphereCount; } public class ConfigAuthoring : MonoBehaviour { public GameObject SpherePrefab; public int SphereCount; } public class ConfigBaker : Baker { public override void Bake(ConfigAuthoring authoring) { AddComponent(new Config { SpherePrefab = GetEntity(authoring.SpherePrefab), SphereCount = authoring.SphereCount, }); } } public partial struct SphereSpawningSystem : ISystem { [BurstCompile] public void OnUpdate(ref SystemState state) { var config = SystemAPI.GetSingleton(); var ecbSingleton = SystemAPI.GetSingleton(); var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged); for (int i = 0; i < config.SphereCount; i++) { var entity = ecb.Instantiate(config.SpherePrefab); ecb.SetComponent(entity, new LocalTransform { Position = new float3(0, i * 2, 0), Rotation = quaternion.identity, Scale = 1 }); } // This system should only run once at startup. So it disables itself after one update. state.Enabled = false; } } ``` -------------------------------- ### SetFrictionToZeroSystem: IJacobiansJob example Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/simulation-modification.html Schedules an IJacobiansJob to zero out friction on contact jacobians. The job runs on a single thread; use ScheduleParallel() for multi-threaded execution. ```csharp [BurstCompile] [UpdateInGroup(typeof(PhysicsSimulationGroup))] [UpdateAfter(typeof(PhysicsCreateJacobiansGroup))] [UpdateBefore(typeof(PhysicsSolveAndIntegrateGroup))] public partial struct SetFrictionToZeroSystem : ISystem { [BurstCompile] public partial struct SetFrictionToZeroJob : IJacobiansJob // Note: there are much more performant ways of setting friction to zero, this is just for demonstration purposes { // Don't do anything for triggers public void Execute(ref ModifiableJacobianHeader h, ref ModifiableTriggerJacobian j) {} [BurstCompile] public void Execute(ref ModifiableJacobianHeader jacHeader, ref ModifiableContactJacobian contactJacobian) { var friction0 = contactJacobian.Friction0; friction0.AngularA = 0.0f; friction0.AngularB = 0.0f; contactJacobian.Friction0 = friction0; var friction1 = contactJacobian.Friction1; friction1.AngularA = 0.0f; friction1.AngularB = 0.0f; contactJacobian.Friction1 = friction1; var angularFriction = contactJacobian.AngularFriction; angularFriction.AngularA = 0.0f; angularFriction.AngularB = 0.0f; contactJacobian.AngularFriction = angularFriction; } } [BurstCompile] public void OnUpdate(ref SystemState state) { state.Dependency = new SetFrictionToZeroJob() .Schedule(SystemAPI.GetSingletonRW(), ref SystemAPI.GetSingletonRW().PhysicsWorld, state.Dependency); } } ``` -------------------------------- ### EnableSurfaceVelocitySystem: IContactsJob example Source: https://docs.unity3d.com/Packages/com.unity.physics%406.6/manual/simulation-modification.html Schedules an IContactsJob to set the EnableSurfaceVelocity flag on contacts. The job runs on a single thread; use ScheduleParallel() for multi-threaded execution. ```csharp [UpdateInGroup(typeof(PhysicsSimulationGroup))] [UpdateAfter(typeof(PhysicsCreateContactsGroup))] [UpdateBefore(typeof(PhysicsCreateJacobiansGroup))] [BurstCompile] public partial struct EnableSurfaceVelocitySystem : ISystem { // This sets some data on the contact, to get propagated to the jacobian // for processing in our jacobian modifier job. This is necessary because some flags require extra data to // be allocated along with the jacobian (e.g., SurfaceVelocity data typically does not exist). [BurstCompile] public partial struct EnableSurfaceVelocityJob : IContactsJob { public void Execute(ref ModifiableContactHeader manifold, ref ModifiableContactPoint contact) { manifold.JacobianFlags |= JacobianFlags.EnableSurfaceVelocity; } } [BurstCompile] public void OnUpdate(ref SystemState state) { state.Dependency = new EnableSurfaceVelocityJob() .Schedule(SystemAPI.GetSingletonRW(), ref SystemAPI.GetSingletonRW().PhysicsWorld, state.Dependency); } } ```