1. The first type of ray: the ray originating from the object itself (this method needs to add the ray component Line Renderer to the object)
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. The second type of ray: the ray of the camera (with the camera as the starting point of the ray)
Note: This ray depends on the tag value MainCamera, without a camera with the tag value of MainCamera, this ray is invalid
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);//输出射线碰撞到的物体的名字
}
}
}
Conclusion: The tree that embraces is born at the end of the hair; the nine-story platform starts from the pile of soil; the journey of a thousand miles begins with a single step.