Raycasting only to a particular object

2019-01-29 12:48发布

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?

标签: unity3d
2条回答
Fickle 薄情
2楼-- · 2019-01-29 13:06

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.

查看更多
放我归山
3楼-- · 2019-01-29 13:09
RaycastHit hit;

if (Physics.Raycast(transform.position, fwd, hit,10) && hit.collider.gameObject.tag == "police" )
{
// do stuff here
}

Note that you need to set the tag of the gameObject from the editor. you could also use gameObject.name .

查看更多
登录 后发表回答