I am trying to write a small Python script in Blender which should be able to detect whether a surface of a mesh is hit by the light or not.
I wrote this code based on some replies and comments. In the scene, you can see two cubes and a light (sun). Obviously, the ray hits first the larger cube, meaning that the smaller cube is shadow. I also get a correct result in terms of location of the hit. But how can I automatically tell that the smaller cube is shadowed? An idea could be to measure the distance between the source and the obstacle (larger cube), and since this is smaller than the distance between the source and the target (smaller cube), I can assume that the smaller cube is in shadow. However, I was just wondering if this makes sense, because I saw other answers where this approach of measuring the distance did not seem to be implemented (e.g. https://blender.stackexchange.com/a/269656/52670)
import bpy
bpy.ops.mesh.primitive_cube_add(enter_editmode=False, align='WORLD', location=(0, 0, 8), scale=(4, 4, 4))
bpy.ops.mesh.primitive_cube_add(enter_editmode=False, align='WORLD', location=(0, 0, 1), scale=(1, 1, 1))
bpy.ops.object.light_add(type='SUN', align='WORLD', location=(0,0, 40), scale=(1, 1, 1))
loc_origin=bpy.data.objects['Sun'].location
loc_target=bpy.data.objects['Cube.001'].location
direction = target-origin
scene = bpy.context.scene
depsgraph = bpy.context.evaluated_depsgraph_get()
result = scene.ray_cast(depsgraph, origin, direction)
print(result[0])
print(result[1])