We can assign constraints to objects through the object “constraints” property.
To add a constraint to the currently active object, we need to create a new constraint in the object’s “constraints” list, specifying its type in the parameters:
1 2 3 |
obj = bpy.context.active_object constraint = obj.constraints.new(type='TRACK_TO') |
Now the constraint’s properties can be configured through the returned result or through the constraint from the object constraints list.
1 2 |
bpy.context.object.constraints[0] # bpy.data.objects['Plane'].constraints["Track To"] |
For example, to make the camera track an object, let’s add a tracking constraint to it:
1 2 3 4 5 6 7 |
import bpy target_obj = bpy.data.objects['Cube'] camera_obj = bpy.data.objects['Camera'] constraint = camera_obj.constraints.new(type='TRACK_TO') constraint.target = target_obj |