美文网首页
Unity Ray射线跟随鼠标

Unity Ray射线跟随鼠标

作者: 114105lijia | 来源:发表于2022-12-26 20:31 被阅读0次
    一、射线跟随鼠标点击位置
    1.gif
    Vector3 hitpoint = Vector3.zero;
    
    void Update()
        {
            ShowClickLine();
        }
    
    void ShowClickLine() {
            // 按下鼠标左键发射射线
            if (Input.GetMouseButtonDown(0))
            {
                // 使用主摄像机创建一根射线,射线的方向是鼠标点击的位置(从摄像头位置到鼠标点击位置的一条射线)
                Vector3 screenPoint = Input.mousePosition;
                ray = Camera.main.ScreenPointToRay(screenPoint);
    
                // 使用物理类检查射线的碰撞,如果点击物体存在
                if (Physics.Raycast(ray, out hit))
                {
                    hitpoint = hit.point;
                }
            }
    
            Debug.DrawRay(transform.position, hitpoint - transform.position, Color.red);
        }
    
    二、射线实时跟随鼠标位置
    2.gif
    void Update()
        {
            ShowLine();
        }
    
    void ShowLine()
        {
            //返回一条射线从摄像机通过一个屏幕点
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo = new RaycastHit();
            //(射线的起点和方向,hitonfo将包含碰到碰撞器的更多信息,射线的长度)有碰撞时,返回真
            if (Physics.Raycast(ray, out hitInfo, 100))
            {
                //显示检测到的碰撞物体的世界坐标
                print(hitInfo.point);
                Debug.DrawLine(transform.position, hitInfo.point, Color.red);
            }
        }
    

    相关文章

      网友评论

          本文标题:Unity Ray射线跟随鼠标

          本文链接:https://www.haomeiwen.com/subject/czmgqdtx.html