Check Physics Core 2D API intersections
To check whether 2D physics objects overlap or will collide, also known as intersections, use query methods.
Read time 2 minutesLast updated 14 days ago
To check whether 2D physics objects overlap or will collide, also known as intersections, use Physics Core 2D API query methods.
Use one of the following methods:
- The API to check for overlaps. For example,
PhysicsQueryto check whether a capsule overlaps with a circle.PhysicsQuery.CapsuleAndCircle - The method of a geometry object to check if it overlaps with another geometry object. For example,
Intersect.CapsuleGeometry.Intersect
The world object also has the following methods:
- Methods that cast rays or shapes. For example, or
PhysicsWorld.CastRay.PhysicsWorld.CastGeometry - Overlap test methods that return true if a point or shape overlaps another object. For example, .
PhysicsWorld.TestOverlapAABB - Overlap methods that return the objects that overlap a point or shape. For example, .
PhysicsWorld.OverlapCircle
All methods are thread-safe. For more information, refer to Optimize the Physics Core 2D API with multithreading.
Example
To cast rays to check whether a shape will collide with other shapes, use the API.
CastGeometryFor example, the following script checks if a small falling circle will collide with objects underneath it. Attach the script to a GameObject and enter Play mode, then use the Big Circle checkbox to toggle an object underneath the falling circle.
using UnityEngine;using Unity.U2D.Physics;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(); }}