Search Unity

Help with Raycasting direction?

Discussion in 'Physics' started by ckgussin, Jan 7, 2018.

  1. ckgussin

    ckgussin

    Joined:
    Oct 30, 2017
    Posts:
    1
    Rays will only detect an object from the origin to a fixed direction, So how can I do it so rays can detect an object from origin to any direction it is being pointed at?

    For example, From the left side. Rays do not detect an object and is not shown in the debug either.http://prntscr.com/hxd8jh http://prntscr.com/hxd8xw

    But from the front, it will detect the object. http://prntscr.com/hxd95k http://prntscr.com/hxd9b6

    Here is the code I currently have at the moment.

    private void FixedUpdate()
    {
    Ray ray = new Ray(transform.position, Vector3.forward);
    RaycastHit hit;


    Physics.Linecast(transform.position, -transform.up * maxRayDistance, Color.red);


    if (Physics.Raycast(ray, out hit, maxRayDistance))
    {
    Debug.DrawRay(transform.position, -transform.up * maxRayDistance, Color.red);

    if (hit.transform.gameObject.tag == "Enemy")
    {

    Debug.Log("You hit a ray");
    rayHitInvis(hit.transform);


    }


    }

    }
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,195
    A couple of things confuse me about your code.
    1. You're calling Linecast, but not doing anything with the result.
    2. When calling Raycast, if successful, you call DrawRay, but you draw a different ray than the one you were just raycasting for. (Your raycast was looking forward, but your DrawRay is drawing a ray downward?
    The pictures you show trying to detect and object from the "left side" don't show any object in the scene to detect. What object were you hoping to detect in the first two screenshots? Because there doesn't seem to be anything there....

    What kind of collider do you have on the object you're hoping to hit?

    As an aside, another approach you could take is to add an invisible cone (no mesh filter) to your object, and make it a trigger collider. Then detect collisions between that cone and your targets. I'm not sure whether that's cheaper than doing several raycasts per frame, but it's a potentially simpler implementation conceptually and in code.

    -Dan
     
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,406
    also this will set ray direction towards forward in world direction,
    Code (CSharp):
    1. Ray ray = new Ray(transform.position, Vector3.forward);
    maybe you want transform forward instead (or others like transform.up, right...)
    Code (CSharp):
    1. Ray ray = new Ray(transform.position, transform.forward);
     
    leozhang1 likes this.