[2D Physics] Replicating CompositeCollider2D with PhysicsComposer
Solution
Unity 2022.3.x - Unity 6.3.x
Published Tue, Apr 28
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.
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:
- Initialize an instance of PhysicsComposer using a
NativeArrayorNativeSliceto hold the initial geometry data. - Invoke
AddLayersto add various geometry types or spans of vertices. This can be done multiple times to stack layers. - Define a
PhysicsComposerOperationfor each layer to determine if the PhysicsComposer should union, subtract, or intersect the shapes. - Execute the generation of
PolygonGeometryto produce the final merged outlines. - Create the final physics representation by calling
PhysicsShape.CreateShapeBatchwith the generated geometry.
Additional Tips
- Utilize PhysicsComposer within an
IJobto ensure that complex geometry calculations do not block the main thread. - Always manage memory manually by calling
Dispose()on the PhysicsComposer and any temporaryNativeArrayused during the generation process. - For advanced usage, reference the
PhysicsComposerGeometrysample 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.