Unity中两种射线的简单使用

1.第一种射线:源自物体本身的射线(该方法需要在物体上添加射线组件Line Renderer)

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

public class CubeLine : MonoBehaviour {
    LineRenderer line;
    // Use this for initialization
    void Start () {
        line=GetComponent<LineRenderer>();
        line.widthMultiplier = 0.08f;//设置射线的宽度
    }
    
    // Update is called once per frame
    void Update () {
        line.SetPosition(0, transform.position);//设置射线的起点
        line.SetPosition(1, transform.forward*10.0f);//设置射线的终点    
    }
}

2.第二种射线:摄像机的射线(以摄像机为射线的起点)

注:这种射线依赖的tag值MainCamera,没有带有MainCamera的tag值的摄像机,这种射线是无效的

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

public class CameraLine : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);//定义射线,以鼠标的位置为终点
        Debug.DrawLine(mouseRay.origin, mouseRay.direction*10.0f,Color.red);//描绘射线,只在Scene视图中看得见
        RaycastHit hitInfo;
        if (Physics.Raycast(mouseRay, out hitInfo))//检测带有碰撞体的物体,其射线终点是与带有碰撞体的物体的交汇处
        {
            print(hitInfo.collider.name);//输出射线碰撞到的物体的名字
        }
    }
}

结语:合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。

猜你喜欢

转载自blog.csdn.net/falsedewuxin/article/details/129466382