I'm trying to write a script to create the beginnings of a music visualizer but I'm having a hard time creating drivers to do it. My basic game plan is this:
- Calculate frequencies and step sizes
- For each frequency step, create a cube.
- Create an empty to go along with it.
- Do some transformations on the cube.
- Add a driver to the cube.
- Link the cube's Z scale with the empty's scale using drivers.
- Create a material that also uses drivers to hook into the empty's scale and use that to animate stuff.
- Bake sound to empty's scale.
- Rinse and repeat until all cubes/empties/materials are created.
The reason I want to use drivers is that my previous approach was to bake the sound to the cube's Z scale then I had another script that would read that information for each frame and then keyframe the cube's material. This led to pretty big file sizes. Larger than it needed to be, anyway. So this time around I figured I'd get around that by using drivers. I've been playing around in the console trying to figure it out and this is what I've got so far:
bpy.ops.mesh.primitive_cube_add(location=(.5, -.5, 0)) # Create a cube
currentcube = bpy.context.active_object # Make sure we can keep track of this cube while we're working on it.
bpy.ops.object.empty_add(location=(.5, -.5, -1)) # Add our control-freak empty.
currentempty=bpy.context.active_object # Make sure we can keep track of this empty while we're working on it.
currentcube.dimensions = (1, 1, 5) # Do some transformations.
bpy.ops.object.transform_apply(scale=True) # Apply the transformations.
fcurve = currentcube.driver_add("scale", 2) # Add a driver to the scaling on the Z axis.
fcurve.driver.type="AVERAGE" # Default is SCRIPTED for some reason.
drivervar = fcurve.driver.variables.new() # Create a new variable on the driver.
And it's at this point that I'm stuck. dir() and autocomplete got me this far but now it's failed me and I'm having a hard time working my way through the docs.
drivervar is a
DriverVariable. From the docs it looks like I need to add a new DriverTarget into
targets, but it's read-only.
But that's okay because while organizing my thoughts and the random code bits I had been trying in the console I found out that there's already a blank target by default at
drivervar.targets and it's not just an empty array like I had assumed. I would like to thank everyone here for the wonderful help and expertise I'm sure you would have provided if I hadn't discovered this on my own.