部分内容由千峰教育(莫新宇)听课笔记总结
物理射线(用于检测碰撞体)
射线类Ray
射线组成部分:起点(origin),方向(direction)
获取鼠标屏幕射线
ScreenPointToRay 将屏幕上的一个点转换成射线
发射射线
Raycast 发射物理射线,返回一个碰撞检测对象RaycastHit
RaycastAll 发射物理射线,返回所有碰撞检测对象RaycastHit
RaycastHit
包括collider(碰撞物体的Collider组件)和point(碰撞点坐标)两个属性
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayDemo : MonoBehaviour {
private Ray ray;
private RaycastHit hit;
// Use this for initialization
void Start () {
//实例化射线
ray = new Ray(Vector3.up,Vector3.right);
}
// Update is called once per frame
void Update () {
//发射射线并检测到了
if (Physics.Raycast(ray,out hit)) { Debug.Log(hit.collider); }
Debug.DrawRay(ray.origin,ray.direction,Color.red);
}
}
检测碰撞点
void Update () {
//发射射线并检测到了
if (Physics.Raycast(ray,out hit)) { Debug.Log(hit.point); }
//ray.direction射线的方向向量 *10表示长度
Debug.DrawRay(ray.origin,ray.direction*10,Color.red);
}
可以通过改变方向向量来控制长度
void Update () {
//发射射线并检测到了
if (Physics.Raycast(ray,out hit)) { Debug.Log(hit.point); }
//ray.direction射线的方向向量 *10表示长度
Debug.DrawRay(ray.origin,ray.direction*(10),Color.red);
}
2*3视图下,摄像机与碰撞点间的连线,仅在开发者视图可以看到
public class RayDemo : MonoBehaviour {
// Update is called once per frame
private RaycastHit hit;
private Ray ray;
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Debug.DrawLine(Camera.main.transform.position, hit.point, Color.red);
}
}
}