这个光线投射有什么问题?

What is wrong with this raycast?

我在代码中使用相同的光线投射进行拾取和放下。当我把光标放在项目上时,他第一次点击它下面的方块。当我再次拿起它并想把它放在同一个地方时,他只击中了物品而不是它下面的方块。我不明白,因为该项目两次在光标处的位置相同。

if (Input.GetMouseButtonDown(0)) {
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   RaycastHit hit;
   if (Physics.Raycast(ray, out hit)) {
      Debug.Log(hit.transform.name);
   }
}

输出:

Diamond(Clone)
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

Square_3_10
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

Diamond(Clone)
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

Diamond(Clone)
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

观看视频: https://drive.google.com/file/d/1S8iF3gYcMDmo1WwZlb1H21d-n8cTn2R-/view?usp=sharing

首先,该行为是由于光线击中 场景中的所有碰撞器 并将第一个命中信息放入 RaycastHit.

有几种方法可以做到这一点。

  1. 使用图层蒙版
  2. 放下钻石时禁用对撞机(但您想再次拖放,不是吗?

The first one is the best so 定义一个 LayerMask 并在钻石掉落后将其处理到您的逻辑中。

int squareMask = 10;
int maxDistance = 100;
if (Physics.Raycast(ray, out hit, maxDistance, squareMask)) {
    // process here
}