在这里提供两种方案,一种是射线检测,另一种是非射线检测。
初始准备步骤:
- 创建2D对象(比如2D精灵)
- 给要被检测的2D对象添加2D碰撞体(必须是2D碰撞体)
- 创建一个空对象,再创建一个检测脚本,将检测脚本挂载在这个空对象上
- 编写检测脚本
一、非射线检测的方式
using UnityEngine;public class DragTest : MonoBehaviour
{private void Update() {if(Input.GetKeyDown(KeyCode.Mouse0)){//将鼠标坐标转化为世界坐标Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);//定义一个2D碰撞体,读取Physics2D.OverlapPoint方法的检测数据Collider2D hitcollider = Physics2D.OverlapPoint(mousePos);if(hitcollider != null){//打印出这个对象的tag名称Debug.Log(hitcollider.gameObject.tag);}}}
}
二、射线检测的方式
using UnityEngine;public class DragTest : MonoBehaviour
{private void Update() {if(Input.GetKeyDown(KeyCode.Mouse0)){//创建一条从屏幕射出的射线Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//获得射线检测命中到的目标RaycastHit2D hit = Physics2D.Raycast(ray.origin,ray.direction,Mathf.Infinity);if(hit.collider != null){Debug.Log(hit.collider.gameObject.tag);}}}
}
三、特别注意
如果有多个2D物体重叠在一起,那么这两种检测方式的最终检测结果都是叠在最上方的2D物体