Adding Constraints to objects.

Hi,

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.

Thanks
Tom

This might get you going.

Run this in the default scene.


import bpy

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

ob = bpy.data.objects["Cube"]
target = bpy.data.objects["Camera"]
addTrackToConstraint(ob,"myTrackTo",target)

Docs here.

Thanks, thats worked. What does the:

print(dir(cns))

part do?

Thanks
Tom

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?

Thanks
Tom

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)”?

Thanks
Tom