Raycasting only to a particular object

前端 未结 2 457
别跟我提以往
别跟我提以往 2020-12-22 06:32

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

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

    if          


        
相关标签:
2条回答
  • 2020-12-22 06:45
    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 .

    0 讨论(0)
  • 2020-12-22 06:52

    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.

    0 讨论(0)
提交回复
热议问题