[Unity]教程------Ray(射线)的基本使用

一、使用射线碰撞物体

     1.准备工作

      在Scene里新建一个Cube,调整位置确保,能在MainCamera里看到它,鼠标也能放在上面(就是确保我们能“触摸”到它)

       2.新建脚本RayTarget(名字谁便起),添加变量Ray和RaycastHit(发生碰撞后需要从RaycastHit里提前信息)

private Ray ray;//从摄像机发出射线(根据鼠标在屏幕位置)
private RaycastHit hitInfo;//获取射线信息

         3.在void Update()中添加碰撞检测

ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从当前鼠标位置发射射线
if (Input.GetMouseButtonDown(0))//鼠标左键按下
{
     if (Physics.Raycast(ray, out hitInfo))//使用默认射线长度和其他默认参数
     {
         Debug.Log("Hit--" + hitInfo.collider.gameObject.name);//碰撞到的物体的名称
     }
}

       4.给Main Camera添加这个脚本

有时候自建camera的时候,脚本里Camera.main会报错为null。这时候只要给Camera添加Tag为MainCamera即可

完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayTarget : MonoBehaviour
{

    private Ray ray;//从摄像机发出射线(根据鼠标在屏幕位置)

    private RaycastHit hitInfo;//获取射线信息

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从当前鼠标位置发射射线
        if (Input.GetMouseButtonDown(0))//鼠标左键按下
        {
            if (Physics.Raycast(ray, out hitInfo))//使用默认射线长度和其他默认参数
            {
                Debug.Log("Hit--" + hitInfo.collider.gameObject.name);//碰撞到的物体的名称
            }
        }
    }
}

二、指定碰撞某个Layer层的某个物体

        1.Layer的简单介绍

         在Unity里,有很多的层,每个层都能摆放很多物体,我们谁便选中一个物体,在它的Inspector页面中可以看到Layer选项(下面的Plane层是我自己加的)

           点开这个Layer,你会看到几个Unity已经分配好的层,如Water、UI等,点击下发的Add Layer,你就可以添加自定义的层,或者你也可以在Project Setting里找到Tags and Layers

 

        2.添加自定义Layer,并给物体分配Layer

        就是随便选择一个能用的Layer添加上它的名称,并将物体的Layer设置为这个,比如我选择Layer8(一定要记好的你层数和名称,后续的脚本里需要使用到)

        3.添加脚本

 private LayerMask  mask;//层的mask
void Start()
{
     mask = 1 << 8;//开启第八层碰撞,其他层无效
     //mask = 1 << LayerMask.NameToLayer("Plane");//同上,Plane是8层的名字
     //mask = ~(1 <<8);//加了一个符合就变成,打开除了第8之外的层
}

 void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);//发射射线
        if (Input.GetMouseButtonDown(0))//鼠标左键按下
        {
            if (Physics.Raycast(ray, out hitInfo, 1000, mask))//射线长度1000,使用mask
            {
                Debug.Log("Hit--" + hitInfo.collider.gameObject.name);
                if(hitInfo.collider.gameObject.name=="Plane")//判断碰撞的物体名字叫不叫Plane
                {
                   
                }
            }
        }
    }

         4.给Main Camera添加这个脚本

猜你喜欢

转载自blog.csdn.net/qq_36251561/article/details/119174801