# How to point a sun lamp using a vector in Python?

It seems this should be easy - I have a long list of normals as a list of tuples in my python script.

[(nx, ny, nz), (nx, ny, nz), (nx, ny, nz)...]

Each tuple represents the direction I want a sun lamp to point for that particular frame of animation.

How do I set the direction of a sun lamp using a vector?

Is there a straightforward python method - maybe in mathutils - that would set sun lamp's matrix so that it points in the direction of the vector?

I've looked there but nothing stands out as far as I can see, though I'm a mathutils noob.

No nodes or plugins, thanks!

There is indeed a straightforward python method using mathutils.

from mathutils import Vector
direction = Vector(your_tuple)
your_object.rotation_mode = 'QUATERNION'
your_object.rotation_quaternion = direction.to_track_quat('Z','Y')

You can see the doc here for more details.

Edit: As the sun direction is negative on the z axis, you may have to change 'Z' to '-Z'

• OK that looks promising and I'll give it a go. What do "track" and "up" mean, or at least refer to?
– uhoh
Commented Oct 9, 2016 at 14:16
• I'm guessing that "track" refers to the axis the sun points at when it has never been rotated. If the sun lamp was created pointing towards the X axis you would have to change 'Z' to 'X'. Commented Oct 9, 2016 at 14:35
• OK This is going well so far - thank you very much! I think I understand what you mean - I'll do some experimentation, but so far it seems to be working. I'm actually using the same tuple for the Sun or Moon position as I use for the sun lamps directions - and not the negative values as I thought. This is a silly image physically, but the shadows are right (Moon's shadow is yellow, Suns shadow is blue, and spheres shadow their own lamps) i.sstatic.net/z53AL.png I use Skyfield to get the positions. Thanks!
– uhoh
Commented Oct 9, 2016 at 14:48
• If I use Area.001.rotation_mode = 'QUATERNION' it fails with >>> Area.001.rotation_mode = 'QUATERNION' File "<blender_console>", line 1 Area.001.rotation_mode = 'QUATERNION' ^ SyntaxError: invalid syntax Commented Sep 25, 2021 at 12:47