Note: This documentation is about writing C# scripts using the LowLevelPhysics2D API. To use 2D physics in the Unity Editor using components like the Rigidbody 2D component, refer to 2D physics instead.
To check whether 2D physics objects overlap or will collide, also known as intersections, use LowLevelPhysics2D API query methods.
Use one of the following methods:
PhysicsQuery API to check for overlaps. For example, PhysicsQuery.CapsuleAndCircle to check whether a capsule overlaps with a circle.Intersect method of a geometry object to check if it overlaps with another geometry object. For example, CapsuleGeometry.Intersect.The world object also has the following methods:
PhysicsWorld.CastRay or PhysicsWorld.CastGeometry.PhysicsWorld.TestOverlapAABB.PhysicsWorld.OverlapCircle.All methods are thread-safe. For more information, refer to Optimize the LowLevelPhysics2D API with multithreading.
Important: These methods return NativeArray types, which you must dispose of to free the memory they use. For more information, refer to Destroy objects and manage memory.
To cast rays to check whether a shape will collide with other shapes, use the CastGeometry API.
For example, the following script checks if a small falling circle will collide with objects underneath it. Attach the script to a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary and enter Play mode, then use the Big Circle checkbox to toggle an object underneath the falling circle.
using UnityEngine;
using UnityEngine.LowLevelPhysics2D;
using Unity.Collections;
public class CastGeometryExample : MonoBehaviour
{
private PhysicsWorld world;
public bool BigCircle;
void Start()
{
world = PhysicsWorld.defaultWorld;
// Create a small falling circle
CircleGeometry object1Geometry = CircleGeometry.Create(0.5f, new Vector2(0.5f, 8f));
PhysicsBody object1 = world.CreateBody(new PhysicsBodyDefinition
{
position = object1Geometry.center,
type = PhysicsBody.BodyType.Dynamic
});
object1.CreateShape(object1Geometry);
if (BigCircle)
{
// Create a larger static circle below
CircleGeometry object2Geometry = CircleGeometry.Create(3f, new Vector2(0f, 0f));
PhysicsBody object2 = world.CreateBody(new PhysicsBodyDefinition
{
position = object2Geometry.center,
type = PhysicsBody.BodyType.Static
});
object2.CreateShape(object2Geometry);
}
// Set translation and filter for the cast
Vector2 translation = new Vector2(0, -10f); // Move downwards
PhysicsQuery.QueryFilter filter = new PhysicsQuery.QueryFilter();
// Cast the circle geometry through the world
NativeArray<PhysicsQuery.WorldCastResult> results = world.CastGeometry(object1Geometry, translation, filter, PhysicsQuery.WorldCastMode.Closest, Allocator.Temp);
if (results.Length > 0)
{
Debug.Log("Collision will occur!");
}
// Dispose of the NativeArray to free memory
results.Dispose();
}
}