Yet another way in which Python is magic—this scene of exploding lights would have taken me hours to model if I was manually, painstakingly inputting keyframes for every object.
Python can do it in less than 2 minutes.
This probably isn’t so surprising given that we’ve already looped hundreds of lights through a scene. This week, I’m using loops to make them move.
Blender Commands to Note
#Set an object’s location (object name = obj)
#Insert Location Data for a Specified Frame (object name = obj)
#Access All Selected Objects in a Loop
for obj in bpy.context.selected_objects:
do this to obj
Alright, How About Some Gently Expanding Lights?
Last week’s post ended with about 200 lights of different sizes randomly placed through a scene. That’s where we’ll start off.
Step 1. Push the lights onto their own layer and deselect all other layers. Then press A to select the just the lights.
Step 2. Fire up the Python console. Loop through the selected objects to set the final keyframes at Frame 100. Like so.
Step 3. Loop through the objects to set their location at the center and set the initial keyframes at Frame 1. Like so.
Barring any typos, this is the result:
That’s nice. But What If I Want Something More Erratic?
Here’s where the Random Module from last week comes in handy again. Start over with the lights randomly placed through the scene with an initial keyframe set at frame 1 (as we did above).
Then type this into the console. This script will loop random numbers into the x,y,z variables of each object so that each light gets its own unique path through the scene.
import random x=4 y=4 z=4 for obj in bpy.context.selected_objects: obj.location=x,y,z obj.keyframe_insert(data_path=”location”, frame=150) x=random.randint(-5,5) y=random.randint(-8,8) z=random.randint(0,8)
What If I Want to Change Up the Size or Rotation?
Scale works much like location—it take 3 parameters for sizing along the x, y, z axis. The first two lines set the scale keyframe for the lights at frame 100 as is. The last three lines set all the lights to a scale of 0 and insert a scale keyframe at frame 150.
for obj in bpy.context.selected_objects: obj.keyframe_insert(data_path=”scale”, frame=100) >>> for obj in bpy.context.selected_objects: obj.scale=0,0,0 obj.keyframe_insert(data_path=”scale”, frame=150)
That’ll get you here:
Combine the scale and random location scripts for the effect in the first gif.