UGUI Image的2d碰撞检测

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011484013/article/details/62040808

2d的碰撞检测和3d的碰撞检测比较相似,发生碰撞的两个对象至少有一个带有刚体组件,两个对象都要有碰撞器,和3d不同之处在于2d碰撞的刚体使用的是rigidbody2D,碰撞器使用的是BoxCollider2D。

操作示例:
1创建2个Image,然后给它们都挂载BoxCollider2D组件,随便选择一个挂载rigidbody2D组件。
2 调节BoxCollider2D的大小,使其与图片的尺寸保持一致。默认加载的BoxCollider2D比较小,边长都为1.
调节刚体属性,gravity scale设置为0,不使用重力效果
这里写图片描述
这里写图片描述

3添加碰撞检测方法

using UnityEngine;
using System.Collections;

public class ColloderTest : MonoBehaviour {

    void OnCollisionEnter2D(Collision2D coll) {
        Debug.Log ("-------开始碰撞------------");
        Debug.Log(coll.gameObject.name);
    }

    void OnCollisionStay2D(Collision2D coll) {
        Debug.Log ("------正在碰撞-------------");
        Debug.Log(coll.gameObject.name);
    }

    void OnCollisionExit2D(Collision2D coll) {
        Debug.Log ("------结束碰撞-------------");
        Debug.Log(coll.gameObject.name);
    }
}

运行结果:
这里写图片描述

4勾选任意一个BoxColloder 2D 的 isTrigger,测试触发方法

    // 开始接触
    void OnTriggerEnter2D(Collider2D collider) {
        Debug.Log("开始接触");
        Debug.Log (collider.name);
    }

    // 接触结束
    void OnTriggerExit2D(Collider2D collider) {
        Debug.Log("接触结束");
        Debug.Log (collider.name);
    }

    // 接触持续中
    void OnTriggerStay2D(Collider2D collider) {
        Debug.Log("接触持续中");
        Debug.Log (collider.name);
    }

运行结果
这里写图片描述
demo下载:http://download.csdn.net/detail/u011484013/9780457

猜你喜欢

转载自blog.csdn.net/u011484013/article/details/62040808