在这里提供两种方案,一种是射线检测,另一种是非射线检测。

初始准备步骤:

  1. 创建2D对象(比如2D精灵)
  2. 给要被检测的2D对象添加2D碰撞体(必须是2D碰撞体
  3. 创建一个空对象,再创建一个检测脚本,将检测脚本挂载在这个空对象上
  4. 编写检测脚本

一、非射线检测的方式

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物体

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部