Version: Unity 6.7 Beta (6000.7)
LanguageEnglish
  • C#

IContactCallback

interface in Unity.U2D.Physics

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

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); } }

Public Methods

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.