仅对特定对象进行光线投射 [英] Raycasting only to a particular object

查看:65
本文介绍了仅对特定对象进行光线投射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下命令检测化身前面是否有东西:

void Start()
{
    Vector3 fwd = transform.TransformDirection(Vector3.forward);

    if (Physics.Raycast(transform.position, fwd, 10))
        Debug.Log("Something in front");
}

现在,我试图找出只有一个特定对象在前面,例如,层次结构中另一个名为Police的化身:

public class CharAnim : MonoBehaviour
{

  police = GameObject.Find("Police");

  void Start()
  {
      Vector3 fwd = transform.TransformDirection(Vector3.forward);

      if (Physics.Raycast(transform.position, fwd, 10))
          Debug.Log("Something in front");
  }

}

但是,从文档中,我看不到是否可以使用此police变量通过射线投射,测量到它的距离等来检测它...

我该如何实现?

解决方案

最后一个答案没有考虑到事物实际上可以阻挡光线投射,甚至无法到达您想要的物体.

>

您必须首先为要检测自定义的对象提供图层.

然后,您必须进行光线投射,该光线投射将使除所需的层之外的所有层都穿透忽略,例如:

请注意:此示例假定您使用了自定义图层#9 :

float distance = 10;
int layer = 9;
int layerMask = 1<<layer;

if (Physics.Raycast(transform.position, fwd, distance, layerMask))
      Debug.Log("Something in front");

除非答案真正解决了问题,否则您实际上不应将其标记为接受,因为带有标记为接受的答案的问题所受到的关注会大大减少,否则他们可能会为您解决该问题.

I use the following to detect if something is in front of my avatar:

void Start()
{
    Vector3 fwd = transform.TransformDirection(Vector3.forward);

    if (Physics.Raycast(transform.position, fwd, 10))
        Debug.Log("Something in front");
}

Now, I am trying to find out if only a specific object is in front, for example another avatar with the name Police in the hierarchy:

public class CharAnim : MonoBehaviour
{

  police = GameObject.Find("Police");

  void Start()
  {
      Vector3 fwd = transform.TransformDirection(Vector3.forward);

      if (Physics.Raycast(transform.position, fwd, 10))
          Debug.Log("Something in front");
  }

}

However, from the documentation, I cannot see if it is possible to use this police variable to detect it through ray-casting, measuring distance to it, etc...

How do I implement this?

解决方案

The last answer doesn't take into account that things can actually block the raycast from even reaching your desired object.

You must first give the object you want to detect a custom layer.

Then you have to shoot a raycast which will penetrate and ignore all layers except for the desired one, like so:

Please note: This example assumes you used custom layer #9:

float distance = 10;
int layer = 9;
int layerMask = 1<<layer;

if (Physics.Raycast(transform.position, fwd, distance, layerMask))
      Debug.Log("Something in front");

You really shouldn't mark answers as accepted unless they have actually solved the problem, because questions with answers marked as accepted receive substantially less attention from people who would otherwise potentially be able to solve it for you.

这篇关于仅对特定对象进行光线投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆