UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

physics

[2D Physics] Replicating CompositeCollider2D with PhysicsComposer

Solution

physicsgeometryoptimizationcollision

Unity 2022.3.x - Unity 6.3.x

Published Tue, Apr 28

Issue

 Developers need to implement functionality similar to a CompositeCollider2D for Tilemap assets using the Unity 6 low-level physics system, specifically querying if PhysicsComposer is the appropriate replacement.

Explanation

PhysicsComposer is designed to replicate and extend the functionality of CompositeCollider2D by providing a high-performance PhysicsComposer pipeline compatible with the C# Job System. This system offers greater flexibility by allowing the definition of multiple layers of geometry for complex merging or subtraction operations.

To implement this workflow:

  1. Initialize an instance of PhysicsComposer using a NativeArray or NativeSlice to hold the initial geometry data.
  2. Invoke AddLayers to add various geometry types or spans of vertices. This can be done multiple times to stack layers.
  3. Define a PhysicsComposerOperation for each layer to determine if the PhysicsComposer should union, subtract, or intersect the shapes.
  4. Execute the generation of PolygonGeometry to produce the final merged outlines.
  5. Create the final physics representation by calling PhysicsShape.CreateShapeBatch with the generated geometry.

Additional Tips

  • Utilize PhysicsComposer within an IJob to ensure that complex geometry calculations do not block the main thread.
  • Always manage memory manually by calling Dispose() on the PhysicsComposer and any temporary NativeArray used during the generation process.
  • For advanced usage, reference the PhysicsComposerGeometry sample in the Unity 2D Physics Primer project.

TL;DR

PhysicsComposer provides a high-performance, job-compatible alternative to CompositeCollider2D by allowing multi-layered geometry merging and PolygonGeometry generation.


Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.