【问题标题】:Unity2D Overlap Circle LayerMask not workingUnity2D重叠圆LayerMask不起作用
【发布时间】:2022-01-21 11:37:32
【问题描述】:

我想检查播放器对象的某个半径内是否可交互。为此,我使用 Physics2D.OverlapCircle 检查玩家附近的 2DColliders。我不太清楚为什么参数 LayerMask.NameToLayer("Interactable") 没有检测到任何东西,尽管该层上有对象。如果删除第三个参数,它会检测到玩家是最近的

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckInteractable : MonoBehaviour
{
    void Update()
    {
        Collider2D checkRadius = Physics2D.OverlapCircle(transform.position, 5, LayerMask.NameToLayer("Interactable"));       

        if (checkRadius != null)
        {
            print(checkRadius.ToString());        

        }
    }
}

To string is not printed despite there being objects in the interactable layer

【问题讨论】:

标签: c# unity3d


【解决方案1】:

LayerMask 有点棘手。 LayerMask.NameToLayer 返回的东西返回一个索引而不是一个图层掩码。

你看,图层掩码实际上是位掩码,因此索引不是给定位掩码的结果。 More info here

您可以使用LayerMask.GetMask方法通过代码创建一个,甚至可以添加一个LayerMask序列化成员变量,以便能够在编辑器中创建掩码

希望有所帮助;)

【讨论】:

    【解决方案2】:

    你需要使用 LayerMask.GetMask()

    LayerMask.GetMask("Interactable")
    

    【讨论】:

      【解决方案3】:

      我能够解决问题。我最终使用了 CircleOverlap 的 int 数组版本。然后我将它设置为公共变量,发现“使用图层蒙版”设置为 false,这意味着虽然设置了蒙版,但它没有激活。

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class CheckInteractable : MonoBehaviour
      {
          public float detectionRadius;
      
          public ContactFilter2D contactFilter = new ContactFilter2D();
      
          void Update()
          {
              Collider2D[] results = new Collider2D[5];
              int objectsDetected = Physics2D.OverlapCircle(transform.position, detectionRadius, contactFilter, results);    
      
              if (objectsDetected > 0)
              {
                  print(results[0] + "\t" + results[1] + "\t" + results[2]);
              }
          }
      }
      

      Use Mask Layer is now set to true

      【讨论】:

      • 这是我的解决方案,但我必须等待 2 天才能将其设置为一个:/
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      相关资源
      最近更新 更多