An interface that when implemented, can be called as a target by PhysicsWorld.SendContactCallbacks.
Unity calls OnContactBegin2D and OnContactEnd2D on the main thread after the simulation finishes.
Additional resources: PhysicsWorld.SendContactCallbacks, ITriggerCallback
using UnityEngine; using Unity.U2D.Physics;
// Add the PhysicsCallbacks.IContactCallback interface. public class DetectCollisions : MonoBehaviour, PhysicsCallbacks.IContactCallback { void Start() { PhysicsWorld world = PhysicsWorld.defaultWorld;
// Create a small falling circle. PhysicsBody object1 = world.CreateBody(new PhysicsBodyDefinition { position = new Vector2(0.5f, 8f), type = PhysicsBody.BodyType.Dynamic }); PhysicsShape objectShape1 = object1.CreateShape(CircleGeometry.defaultGeometry);
// Create a larger static circle below. PhysicsBody object2 = world.CreateBody(new PhysicsBodyDefinition { position = new Vector2(0f, 0f), type = PhysicsBody.BodyType.Static }); object2.CreateShape(new CircleGeometry { radius = 3f });
// Set object 1 to activate collisions. objectShape1.contactEvents = true; objectShape1.callbackTarget = this; }
// Log when the small circle collides. public void OnContactBegin2D(PhysicsEvents.ContactBeginEvent eventData) { var contact = eventData.contactId.contact; Debug.Log("Collision started between shapes: " + contact.shapeA + " and " + contact.shapeB); }
// Log when the small circle stops colliding. public void OnContactEnd2D(PhysicsEvents.ContactEndEvent eventData) { var contact = eventData.contactId.contact; Debug.Log("Collision ended between shapes: " + contact.shapeA + " and " + contact.shapeB); } }
| Method | Description |
|---|---|
| OnContactBegin2D | Called when a ContactBeginEvent for the object occurs. This will always be called on the main-thread after the simulation has finished. |
| OnContactEnd2D | Called when a ContactEndEvent for the object occurs. This will always be called on the main-thread after the simulation has finished. |