当此碰撞器/刚体开始接触另一个刚体/碰撞器时,将调用 OnCollisionEnter。
与 OnTriggerEnter 相反,OnCollisionEnter 传递的是 Collision 类,而不是 Collider。该 Collision 类包含有关接触点、冲击速度等的信息。如果您在函数中不使用 collisionInfo,请省略 collisionInfo 参数,因为这将避免不必要的计算。注意:只有当其中一个碰撞器还附加了非运动学刚体时,才会发送碰撞事件。碰撞事件将发送到禁用的 MonoBehaviour,以允许在响应碰撞时启用 MonoBehaviour。
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { AudioSource audioSource;
void Start() { audioSource = GetComponent<AudioSource>(); }
void OnCollisionEnter(Collision collision) { // Debug-draw all contact points and normals foreach (ContactPoint contact in collision.contacts) { Debug.DrawRay(contact.point, contact.normal, Color.white); }
// Play a sound if the colliding objects had a big impact. if (collision.relativeVelocity.magnitude > 2) audioSource.Play(); } }
另一个示例
// A grenade // instantiates a explosion Prefab when hitting a surface // then destroys itself using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { public Transform explosionPrefab; void OnCollisionEnter(Collision collision) { ContactPoint contact = collision.contacts[0];
// Rotate the object so that the y-axis faces along the normal of the surface Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal); Vector3 pos = contact.point; Instantiate(explosionPrefab, pos, rot); Destroy(gameObject); } }