一、射线跟随鼠标点击位置
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);
}
}
网友评论