其他 | 参与此碰撞的另一个 Collider2D。 |
当另一个对象进入连接到此对象的触发碰撞体时发送(仅限 2D 物理)。
在调用期间传递的 Collider2D 参数中报告了有关另一个碰撞体的更多信息。
触发事件将发送到已禁用的 MonoBehaviour,以允许对行为启用 行为以响应碰撞。
其他资源:Collider2D 类和 OnTriggerExit2D 和 OnTriggerStay2D 消息。
显示一个 OnTriggerEnter2D 示例。此示例有两个空的 GameObject,称为 GameObject1
和 GameObject2
。这两个脚本文件都让示例起作用。第一个脚本 Example1
,创建一个 Sprite 并添加一个 BoxCollider2D 和一个 Rigidbody2D。此对象在地心引力作用下会与 Example2
相遇。 Example2
没有可见性。(它所创建的矩形在场景窗口中可见。)两个 GameObject 报告碰撞。
以下脚本是 Example1。
using System.Collections; using System.Collections.Generic; using UnityEngine;
// Create GameObject1 that falls under gravity. It will pass through // Example2 and cause a collision. GameObject1 is moved back to // the start position and it will again start to fall under gravity.
public class Example1 : MonoBehaviour { void Awake() { SpriteRenderer sr; sr = gameObject.AddComponent<SpriteRenderer>() as SpriteRenderer; sr.color = new Color(0.9f, 0.9f, 0.1f, 1.0f);
BoxCollider2D bc; bc = gameObject.AddComponent<BoxCollider2D>() as BoxCollider2D; bc.size = new Vector2(1.0f, 1.0f);
Rigidbody2D rb; rb = gameObject.AddComponent<Rigidbody2D>() as Rigidbody2D; rb.gravityScale = 1.0f;
// A square in the Resources folder is used. gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("square");
// GameObject1 starts 3 units in the Up direction. gameObject.transform.position = new Vector3(0.0f, 3.0f, 0.0f); gameObject.transform.localScale = new Vector3(0.5f, 0.5f, 1.0f); }
private float timer = 0.0f; private bool restart = false;
void FixedUpdate() { if (restart == true) { timer = timer + Time.deltaTime; if (timer > 0.25f) { gameObject.transform.position = new Vector3(0.0f, 3.0f, 0.0f); gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(0.0f, 0.0f); restart = false; } } }
// called when this GameObject collides with GameObject2. void OnTriggerEnter2D(Collider2D col) { Debug.Log("GameObject1 collided with " + col.name); restart = true; timer = 0.0f; } }
这是 Example2
,作为第二个 GameObject 的碰撞脚本
using System.Collections; using System.Collections.Generic; using UnityEngine;
// Create a rectangle that the other GameObject will collide with. // Note that this GameObject has no visibility. // (View in the Scene view to see this GameObject.)
public class Example2 : MonoBehaviour { void Awake() { BoxCollider2D bc; bc = gameObject.AddComponent<BoxCollider2D>() as BoxCollider2D; bc.size = new Vector2(3.0f, 1.0f); bc.isTrigger = true;
gameObject.transform.localScale = new Vector3(3.0f, 1.0f, 1.0f); gameObject.transform.position = new Vector3(0.0f, -2.0f, 0.0f); }
void OnTriggerEnter2D(Collider2D col) { Debug.Log("GameObject2 collided with " + col.name); } }