Unity是用 int32來表示32個Layer層,int32用二進制來表示一共有32位。html
0000 0000 0000 0000 0000 0000 0000 0000ide
31 0ui
LayerMask mask = 1<<2;
其中 <<左邊的 1表示有[開啓],0表示沒有該layer[忽略] 。右邊的2表示左移2位便是 layer2層的位置。spa
LayerMask mask = 1 << 0 | 1 << 2;
LayerMask mask = 1 << 0 | 0 << 2
LaserMask mask=1 << LayserMask.NameToLayer(「Default」);
下面是一個腳本例子,把它綁定在Camera上code
using UnityEngine; using System.Collections; [RequireComponent(typeof(Camera))] public class LayerMaskTest : MonoBehaviour { //打開Npc層,變1 或 運算符 private void Show() { //camera.cullingMask |= 1 << LayerMask.NameToLayer("Npc"); camera.cullingMask = (int) 1<<LayerMask.NameToLayer("Npc");//寫法二 } // 關閉Npc層,變0 按位與 & 按位取反 ~ private void Hide() { camera.cullingMask &= ~(1 << LayerMask.NameToLayer("Npc")); } // 開關Npc層,按位異或 ^ private void Toggle() { camera.cullingMask ^= 1 << LayerMask.NameToLayer("Npc"); } void OnGUI() { if (GUILayout.Button("Show")) Show(); if (GUILayout.Button("Hide")) Hide(); if (GUILayout.Button("Toggle")) Toggle(); } }
static bool Raycast(Vector3 origin, Vector3 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);
咱們項目中本身寫的物理碰撞互斥orm
//開啓Npc層的碰撞 LayerMask mask = 1 << (int)GameLayerDef.Npc; float bounds = 2; RaycastHit2D raycastHit = Physics2D.CircleCast(transform.position, bounds, Vector2.right, Mathf.Infinity, mask.value);
部份內容參考自: 【風宇衝】二進制:四 Unityhtm