Script for spotlight direction control

I have been starting to use blender , avoiding the GUI almost entirely and doing only scripting. To do the lighting I have been using:

def lights(light_pos,color=(1,1,1,1),energy=5):
#    light types:
#    POINT Point, Omnidirectional point light source.
#    SUN Sun, Constant direction parallel ray light source.
#    SPOT Spot, Directional cone light source.
#    AREA Area, Directional area light source.

    name = 'light1'
    light_data = bpy.data.lights.new(name=name, type='SUN')
    light_obj = bpy.data.objects.new(name=name, object_data=light_data)
    light_obj.location = light_pos
    light_obj.color = color
#    light_obj.rotation = (0,0,radians(-90))
    #direction = Vector(np.random.uniform(low=-1, size=3))
    #light_obj.rotation_mode = 'QUATERNION'
    #light_obj.rotation_quaternion = direction.to_track_quat('-Z', 'Y')
    scene.collection.objects.link(light_obj)  # make the light actually appear in the scene
    bpy.context.view_layer.objects.active = light_obj
    bpy.context.object.data.energy = energy

The color seems to be ignored, and I can’t figure out how to set the direction, limiting me to SUN (and possibly AREA) . Any tips on better blender coding also appreciated.

1 Like