Search Unity

Help with Raycasting direction?

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

  1. ckgussin


    Oct 30, 2017
    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.

    But from the front, it will detect the object.

    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,;

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

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

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



  2. dgoyette


    Jul 1, 2016
    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.

  3. mgear


    Aug 3, 2010
    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.