碰撞检测
发生碰撞检测的前提:
-
碰撞的物体需要有Rigidbody组件和boxcllidder组件
-
被碰撞的物体需要有boxcollider组件
示例1:被碰撞的物体拥有Rigidbody组件
两个物体会因为都具有刚体的组件而发生力的作用,如下图所示,当被碰撞的物体被碰撞时,两物体的刚体组件(Rigidbody组件)发生力的作用,从而达到gris(3)推着gris(1)向左移动的效果
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NO18_Collider : MonoBehaviour
{
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime,Space.World);
}
private void OnCollisionEnter2D(Collision2D collision)
{
print("碰撞的物体为" + collision.gameObject.name);
}
}
示例2:被碰撞的物体没有Rigidbody组件
被碰撞的物体没有刚体组件(Rigidbody组件),因此gris(3)不会推着gris(1)向左移动
触发检测
发生触发检测的前提:
-
碰撞的物体需要有Rigidbody组件和boxcllidder组件
-
被碰撞的物体需要有boxcollider组件并勾选IsTrigger选项
示例:
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NO18_Collider : MonoBehaviour
{
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime,Space.World);
}
private void OnCollisionEnter2D(Collision2D collision)
{
print("碰撞的物体为" + collision.gameObject.name);
}
private void OnTriggerEnter2D(Collider2D collision)
{
print(collision.gameObject.name + "进入了");
}
private void OnTriggerStay2D(Collider2D collision)
{
print(collision.gameObject.name + "停留");
}
private void OnTriggerExit2D(Collider2D collision)
{
print(collision.gameObject.name + "走出了");
}
}