Unity 游戏中的红外线,射线检测

游戏中比如RPG游戏,当我们点击地图的时候,人物跟着就去了点击的地点,这个过程也可以是我们点击屏幕,一道射线从摄像机的平面中发射,指到我们点击的地点。 

例如:我们点击某一处,球体就到某一处

创建一个脚本挂载到球体身上 

脚本:

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

public class RayTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //方式一
        //Ray ray = new Ray(Vector3.zero, Vector3.up);
        //方式二
        //通过摄像机获得射线,ScreenPointToRay 从屏幕点开始发射射线 Input.mousePosition 鼠标按到的点
        //Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    }

    // Update is called once per frame
    void Update()
    {
        //按住鼠标左键发射射线
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //声明一个碰撞信息类
            RaycastHit hit;
            //碰撞检测
            //Physics.Raycast物理类里面一个射线检测方法,out hit 注意out+空格是C#里面的语法,我们声明了信息类,而out会帮助我们填写内容
            bool res = Physics.Raycast(ray, out hit);
            //如果碰撞到的情况下,hit就有内容了,反之就没有内容了
            if (res)
            {
                Debug.Log(hit.point);
                transform.position = hit.point;
            }
            //多检测
            //100:检测距离, 1<<10:只检测第十个图层
            RaycastHit[] hit = Physics.RaycastAll(ray, 100, 1<<10);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ssl267422/article/details/128925768