Version: 2021.3

Physics.ContactModifyEvent

切换到手册

参数

value A delegate to call.

描述

Subscribe to this event to be able to customize the collision response for contact pairs.

Each subscriber to this event gets invoked with a physics scene and a native array of contact pairs to process. Each contact pair has modifiable data, like impulses and contact normals that can be changed in order to customize the bounce behavior.

Only pairs containing Colliders that had Collider.hasModifiableContacts enabled will be passed in the buffer.

Note that this event is called from any thread, so it's advisable to keep copies of all necessary for handling data because only a portion of Unity API is available off the main thread.

Additionally, an event handler can be invoked multiple times per frame, because the physics system distributes all contacts among threads, and only sends a particular amount of contacts per call.

Note: to get contact pairs that have been generated by the CCD solver, subscribe to the Physics.ContactModifyEventCCD event. They are not included in this event.

using Unity.Collections;
using UnityEngine;

public class Test : MonoBehaviour { public float IgnoredRadius = 0.5f; public Vector3 SpawnAt = Vector3.up * 5f;

public void OnEnable() { var ball = GameObject.CreatePrimitive(PrimitiveType.Sphere); GameObject.CreatePrimitive(PrimitiveType.Plane);

ball.transform.position = SpawnAt; ball.AddComponent<Rigidbody>(); ball.GetComponent<SphereCollider>().hasModifiableContacts = true;

Physics.ContactModifyEvent += ModificationEvent; }

public void OnDisable() { Physics.ContactModifyEvent -= ModificationEvent; }

public void ModificationEvent(PhysicsScene scene, NativeArray<ModifiableContactPair> pairs) { // For each contact pair, ignore the contact points that are close to origin foreach (var pair in pairs) { for (int i = 0; i < pair.contactCount; ++i) if (Vector3.Distance(pair.GetPoint(i), Vector3.zero) < IgnoredRadius) pair.IgnoreContact(i); } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961