How to detect if an object is under a shadow casted by a directional light

I’m assuming we can’t treat a directional light as any other form of light, that is as a single point, but as a plane with the same orientation as the directional light. so instead of casting a ray from my object towards the center of the DirectionalLight, I’m casting it from myobject.transform.position to myObject.transform.position - directection of DirectionalLight so that I’m casting lines parallel to the light as in the picture

and if the ray hits a wall on it’s way then set a bool value underSun= true else underSun=false
and to increase the accuracy of the detection, instead of casting a single ray from the center of the object ,I’m casting four each from the it’s top corners


and on everyUpdate if a rayCast from any of these corners doesn’t hit a wall then break and set underSun= true

this does make sense to me, but I’m getting some weird unwanted results with my code and I would appreciate if anyone can point me to the right direction. see in gif below

wanted behaviour

Unwanted Behaviour

the code is here

using UnityEngine;
using System.Collections;

public class NewPlayer : MonoBehaviour {

   
    public NewSun sun;

    private MeshRenderer mesh;
    private RaycastHit hit;
    private bool underSun = false;
    
	// Use this for initialization
	void Start () {
        mesh = GetComponent<MeshRenderer>();
    }
	
	// Update is called once per frame
	void Update () {
        underSun = false;
        Vector3 sunDir = sun.transform.forward;
        sunDir.Normalize();
        sunDir *= 100;
   
        foreach (Transform child in transform) {

            if (!Physics.Raycast(child.position, child.position - sunDir, 30, LayerMask.GetMask("Wall")))
            {

                Debug.DrawLine(child.position, child.position - sunDir, Color.red);
                underSun = true;

            }
            else {
                Debug.DrawLine(child.position, child.position - sunDir, Color.green);
            }
           
        }

       

        if (underSun)
        {
            mesh.material.color = Color.red;
        }
        else {
            mesh.material.color = Color.green;
        }
       

	}
}

Having read @Bonfire-Boy’s comment above, I think I’ve spotted your problem. I’m not sure your Debug.DrawLines are actually visualising your Raycasts correctly. Take a careful look at the function signatures:

  • In Physics.RayCast(), the first two Vector3 parameters are an origin and a direction.
  • In Debug.DrawLine, the first two Vector3 parameters are an origin and an end position.

So, for Debug.DrawLine you’re correct to use child.position - sunDir but, for RayCast, you should be using -1f * sunDir as he suggests.