我是靠谱客的博主 潇洒纸飞机,这篇文章主要介绍unity3d 射线检测RayCast,现在分享给大家,希望可以做个参考。

前言

射线检测即对一个碰撞器进行检测,如果碰撞到碰撞器,则返回true,否则返回false,这个检测是一条射线,这条射线由我们自己设置
一般在Update函数配合if()来使用
RayCast有10多个重载这里以其中一个为例

代码例子

RaycastHit hit 此为射线碰撞到的物体碰撞器,
以out hit传入 当射线碰撞到物体时,返回true,hit则是对应的碰撞物体的碰撞器
可以通过hit来找到碰撞到的物体对象信息

复制代码
1
public static bool Raycast (Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask);
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using UnityEngine; using System.Collections; public class MyHero : MonoBehaviour { //设置层级 : 和当前层级物体进行碰撞检测 public LayerMask _layerMask; void Update(){ //1. 射线开始的位置 //2. 射线的方向 //3. 碰撞信息 //4. 射线的最大距离 //5. 层级 RaycastHit hit; if(Physics.Raycast (transform.position, transform.forward, out hit, 2, _layerMask)){ Debug.Log (hit.collider.gameObject.name); } } void OnDrawGizmos(){ Gizmos.color = Color.red; Gizmos.DrawRay (transform.position, transform.forward * 2); } }

我们可以通过OnDrawGizmos()函数(Gizmos制作测试工具)来把这条射线画出来
该函数不需要通过播放显示,unity编译完既可以显示出一条射线

复制代码
1
2
3
4
void OnDrawGizmos(){ Gizmos.color = Color.red; Gizmos.DrawRay (transform.position, transform.forward * 2); }

1

通过射线使物体移动

  1. 通过鼠标点击的方法,获取Ray类型对象
    _ray = Camera.main.ScreenPointToRay (Input.mousePosition);
  2. 然后根据Ray类型对象做碰撞检测(Plane),得到 RaycastHit _hit
    if (Physics.Raycast (_ray, out _hit))
  3. _hit.point 就是我们要移动到的地方,此时我们用transform.LookAt()看向他,然后设置transform.forward()方法移动到该点。 注意里面的参数是vector3.forward 而不是 transform.forward,这两者在调用时区别挺大。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using UnityEngine; using System.Collections; public class MyMouseTest : MonoBehaviour { Ray _ray; RaycastHit _hit; void Update() { if (Input.GetMouseButton(0)) { _ray = Camera.main.ScreenPointToRay (Input.mousePosition); if (Physics.Raycast (_ray, out _hit)) { Debug.Log ("到该目的地" + _hit.point); } } if (Vector3.Distance (transform.position, _hit.point) < 0.5f) { Debug.Log ("到达目的地"); } else { transform.LookAt (_hit.point); transform.Translate (Vector3.forward * 4 * Time.deltaTime,Space.Self); } } }

最后

以上就是潇洒纸飞机最近收集整理的关于unity3d 射线检测RayCast的全部内容,更多相关unity3d内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部