Unity3D Physics.Raycast 射线检测

本文永久地址:http://www.omuying.com/article/146.aspx, 【文章转载请注明出处!】

Unity3D 提供了 Physics.Raycast 函数,用来检测射线与场景元件的碰撞,最近在处理地图生成 A 星的时候用到了 layerMask 参数,虽然最后完美解决,不过还是要特地记录一下如何更高效的使用 layerMask。

测试场景布局如图:

测试 Demo 代码如下:
01 using UnityEngine;
02 using System.Collections;
03 using System.Text.RegularExpressions;
04  
05 public class Demo : MonoBehaviour
06 {
07     private string checkResult;
08  
09     void Update()
10     {
11         if(!Input.GetKey(KeyCode.LeftShift))
12         {
13             this.Demo1 ();
14         }else
15         {
16             this.Demo2 ();
17         }
18     }
19  
20     void Demo1()
21     {
22         if(Input.GetMouseButtonDown(0))
23         {
24             Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
25  
26             RaycastHit raycastHit; // 射线只检查 Ignore RayCast 和 Ray 层
27             if(Physics.Raycast(ray, out raycastHit, 100, (1 << 2 | 1 << 8)))
28             {
29                 string name = raycastHit.collider.gameObject.name;
30                 checkResult = "元件名称:" + name + ",所在 Layer :" + GetLayerName(name);
31             }else
32             {
33                 checkResult = "未检测到元件!";
34             }
35         }
36     }
37  
38     void Demo2()
39     {
40         if(Input.GetMouseButtonDown(0))
41         {
42             Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
43              
44             RaycastHit raycastHit;  射线只排除 Ignore RayCast 和 Ray 层
45             if(Physics.Raycast(ray, out raycastHit, 100, (~(1 << 2 | 1 << 8))))
46             {
47                 string name = raycastHit.collider.gameObject.name;
48                 checkResult = "元件名称:" + name + ",所在 Layer :" + GetLayerName(name);
49             }else
50             {
51                 checkResult = "未检测到元件!";
52             }
53         }
54     }
55  
56     string GetLayerName(string name)
57     {
58         if(name == "Cube")
59         {
60             return "Default";
61         else if(name == "Ignore RayCast")
62         {
63             return "Sphere";
64         }else if(name == "Capsule")
65         {
66             return "Ray";
67         }else if(name == "Cylinder")
68         {
69             return "TransparentFX";
70         }else if(name == "Plane")
71         {
72             return "UI";
73         }
74         return "";
75     }
76  
77     void OnGUI ()
78     {
79         GUI.Label(new Rect(15, 15,300, 100), "1、直接鼠标点击,射线只会检测到 Ignore RayCast 和 Ray 层的元件。\n2、按住左边 Shift 键同时鼠标点击,射线只会忽略 Ignore RayCast 和 Ray 层的元件!");
80  
81         GUI.Label(new Rect(15, 205,300, 100), checkResult);
82     }
83 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值