3
Name: 'Camera/Object Example'
5
Group: 'ScriptTemplate'
6
Tooltip: 'Script template for setting the camera direction'
9
from Blender import Window
15
Name: 'My Camera script'
18
Tooltip: 'Rotate the camera to center on the active object'
22
from Blender import Window, Scene, Draw, Mathutils
24
# Rotate the camera in such a way that it centers on the currently active object
25
def RotCamToOb(cam, ob):
27
# Get the camera matrix
28
camMat = cam.getMatrix('worldspace');
30
# Get the location of the camera and object and make sure they're vectors
31
camLoc = Mathutils.Vector(cam.loc)
32
obLoc = Mathutils.Vector(ob.loc)
34
# Get the vector (direction) from the camera to the object
35
newVec = obLoc - camLoc
37
# Make a quaternion that points the camera along the vector
38
newQuat = newVec.toTrackQuat('-z', 'y')
40
# Convert the new quaternion to a rotation matrix (and resize it to 4x4 so it matches the other matrices)
41
rotMat = newQuat.toMatrix().resize4x4()
43
# Make a matrix with only the current location of the camera
44
transMat = Mathutils.TranslationMatrix(camMat.translationPart());
46
# Multiply the rotation and translation matrixes to make 1 matrix with all data
47
newMat = rotMat * transMat
49
# Now we make this matrix the camera matrix and voila done!
52
#Make sure blender and the objects are in the right state and start doing stuff
55
# Show a neat waitcursor whilst the script runs
58
# If we are in edit mode, go out of edit mode and store the status in a var
59
emode = int(Window.EditMode())
60
if emode: Window.EditMode(0)
62
# Get the scene, the camera and the currently active object
63
scn = Scene.GetCurrent()
64
cam = scn.getCurrentCamera()
65
ob = scn.getActiveObject()
67
# Lets do some checks to make sure we have everything
68
# And if we don't then call a return which stops the entire script
70
Draw.PupMenu('Error, no active camera, aborting.')
74
Draw.PupMenu('Error, no active object, aborting.')
78
Draw.PupMenu('Error, select an object other than the camera, aborting.')
81
# Start the main function of the script if we didn't encounter any errors
87
# Redraw the 3d view so we can instantly see what was changed
88
Window.Redraw(Window.Types.VIEW3D)
90
# If we were in edit mode when the script started, go back into edit mode
91
if emode: Window.EditMode(1)
93
# Remove the waitcursor
101
new_text = bpy.data.texts.new('camobject_template.py')
102
new_text.write(script_data)
103
bpy.data.texts.active = new_text