Adding Constraints to objects.


Just a quick question, how do you add a constarint to an object using Python? The constraint I want to use is the Track To Constraint. Also the object (that I want to add the constraint too) will also be added from the same script.


This might get you going.

Run this in the default scene.

import bpy

def addTrackToConstraint(ob, name, target):
    cns ='TRACK_TO')
    print(dir(cns)) = name = target
    cns.track_axis = 'TRACK_NEGATIVE_Z'
    cns.up_axis = 'UP_Y'
    cns.owner_space = 'LOCAL'
    cns.target_space = 'LOCAL'

ob =["Cube"]
target =["Camera"]

Docs here.

Thanks, thats worked. What does the:


part do?


Sorry, I almost took that out.

DIR is quite useful for finding out what methods are available for any given variable. If you look in the console you will see the properties and methods for the cns object. But you can ignore that debug line.

Thanks, I’m trying to add the constraint to a lamp, and I was wondering, how do you set the colour of a lamp in Python? Also how did you find out it was cns?


cns is what was returned from the .new() method. A variable of the type constraint.

To find the property for any object, hover your mouse over the Lamp color and wait for the popup to appear. The text in the popup is the RNA path to the property you seek to control or modify via code.

So for a spot light, would it be “SpotLamp.color = (1, 1, 1)”?