unity中Ray、RaycastHit 、Raycast(小白之路)
1.Ray
1 Ray(Vector3 origin, Vector3 direction)
Ray:在程序中可以理解为射线,就是以某个位置(origin)朝某个方向(direction)的一条射线,是一个三维坐标
Ray ray = new Ray(transform.position, transform.forward);
2.RaycastHit
1 RaycastHit hitInfo;
它的结构体如下:
1 public struct RaycastResult 2 { 3 // 4 // Fields 5 // 6 public BaseRaycaster module; // BaseInputModule that raised the hit. 7 8 public float distance; // Distance to the hit. 9 10 public float index; // Hit index. 11 12 public int depth; //The relative depth of the element. 13 14 public int sortingLayer; // The SortingLayer of the hit object. 官方解释的这两个一样,完全不明白 15 16 public int sortingOrder; // The SortingOrder for the hit object. 17 18 public Vector3 worldPosition; // The world position of the where the raycast has hit. 19 20 public Vector3 worldNormal; // The normal at the hit location of the raycast. 21 22 public Vector2 screenPosition; // The screen position from which the raycast was generated. 23 24 // 25 // Properties 26 // 27 public GameObject gameObject { // The GameObject that was hit by the raycast. 28 get; 29 set; 30 } 31 32 public bool isValid { // Is there an associated module and a hit GameObject. 33 get; 34 } 35 36 // 37 // Methods 38 // 39 public void Clear (); 40 41 public override string ToString (); 42 }
它是用于存储射线碰撞到的第一个对象信息,所以需要提前创建这个对象,用于信息的碰撞信息的存储;
3.Raycast
1 public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance, int layermask );
ray:射线结构体的信息,包括起点,方向;也就是一条射线
hitinfo:这条射线所碰撞物体的相关信息;
maxDistance:这条射线的最大距离;
layermask:这条射线在哪层上进行碰撞
这个函数的意思就是:以射线ray经过的maxDistance长度之内,与第一个对象进行的物理碰撞的信息,存储在hitInfo中;如果有碰撞物体,返回true, 反之false;
1.现在我要在一个层中控制人物方向(面对方向就可以这样做)
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if(Physics.Raycast(ray, out hitInfo, 100, groundLayerIndex)) { Vector3 target = hitInfo.point; target.y = transform.position.y; transform.LookAt(target); }
2.如我要接受子弹碰撞信息,并且控制子弹设计方向
1 Ray ray = new Ray(transform.position, transform.forward); 2 RaycastHit hitInfo; 3 if(Physics.Raycast(ray,out hitInfo)) 4 { 5 lineRenderer.SetPosition(1, hitInfo.point); 6 } 7 else 8 { 9 lineRenderer.SetPosition(1, transform.position + transform.forward * 100); 10 }