Animación en Blender
Descripción general
Crea y controla animaciones en Blender usando Python. Anima con fotogramas clave propiedades de objetos y huesos, construye armaduras con rigs IK/FK, anima shape keys para movimiento facial, edita F-Curves para control de tiempo, superpone acciones en el editor NLA y conecta drivers para automatización basada en expresiones, todo desde la terminal.
Instrucciones
1. Fotogramas clave en propiedades de objetos
import bpy
obj = bpy.data.objects["Cube"]
# Fotogramas clave en ubicación en múltiples fotogramas
for loc, frame in [((0,0,0), 1), ((5,0,3), 30), ((5,4,0), 60)]:
obj.location = loc
obj.keyframe_insert(data_path="location", frame=frame)
# También funciona para rotation_euler, scale, un solo eje (index=2 para Z), props personalizadas
obj.rotation_euler = (0, 0, 3.14159)
obj.keyframe_insert(data_path="rotation_euler", frame=60)
obj.scale = (2, 2, 2)
obj.keyframe_insert(data_path="scale", frame=60)
obj["intensity"] = 1.0 # propiedad personalizada
obj.keyframe_insert(data_path='["intensity"]', frame=30)
bpy.context.scene.frame_start, bpy.context.scene.frame_end = 1, 60
2. Control de interpolación y modificadores de F-Curves
import bpy
action = bpy.data.objects["Cube"].animation_data.action
for fcurve in action.fcurves:
for kp in fcurve.keyframe_points:
kp.interpolation = 'BEZIER' # CONSTANT, LINEAR, BEZIER, SINE, EXPO, BOUNCE, ELASTIC
kp.easing = 'EASE_IN_OUT' # AUTO, EASE_IN, EASE_OUT, EASE_IN_OUT
# Modificador de ciclos para repetir la animación
mod = fcurve.modifiers.new(type='CYCLES')
mod.mode_before = 'REPEAT' # NONE, REPEAT, REPEAT_OFFSET, MIRROR
mod.mode_after = 'REPEAT'
# Agregar ruido a un canal específico
z_curve = action.fcurves.find("location", index=2) # ubicación Z
if z_curve:
noise = z_curve.modifiers.new(type='NOISE')
noise.strength, noise.scale = 0.3, 5.0
3. Crear armaduras y huesos
import bpy
arm_data = bpy.data.armatures.new("Rig")
arm_obj = bpy.data.objects.new("Rig", arm_data)
bpy.context.collection.objects.link(arm_obj)
bpy.context.view_layer.objects.active = arm_obj
bpy.ops.object.mode_set(mode='EDIT')
# (nombre, cabeza, cola, nombre_padre, conectado)
huesos_def = [
("Spine", (0,0,1.0), (0,0,1.4), None, False),
("Chest", (0,0,1.4), (0,0,1.8), "Spine", False),
("UpperArm.L", (0.2,0,1.7), (0.5,0,1.4), "Chest", False),
("Forearm.L", (0.5,0,1.4), (0.8,0,1.1), "UpperArm.L", True),
("Thigh.L", (0.1,0,1.0), (0.1,0,0.5), "Spine", False),
("Shin.L", (0.1,0,0.5), (0.1,0,0.05),"Thigh.L", True),
]
for nombre, cabeza, cola, padre, conectado in huesos_def:
b = arm_data.edit_bones.new(nombre)
b.head, b.tail = cabeza, cola
if padre:
b.parent = arm_data.edit_bones[padre]
b.use_connect = conectado
bpy.ops.object.mode_set(mode='OBJECT')
4. Configurar constraints en huesos
import bpy
arm_obj = bpy.data.objects["Rig"]
bpy.context.view_layer.objects.active = arm_obj
bpy.ops.object.mode_set(mode='POSE')
# IK — usar un Empty como objetivo, chain_count limita los huesos afectados
ik = arm_obj.pose.bones["Forearm.L"].constraints.new('IK')
ik.target = bpy.data.objects["IK_Target"]
ik.pole_target = bpy.data.objects["IK_Pole"]
ik.chain_count = 2
# Copy Rotation — refleja la rotación de otro objeto
cr = arm_obj.pose.bones["Chest"].constraints.new('COPY_ROTATION')
cr.target = bpy.data.objects["ChestCtrl"]
# Otros tipos: LIMIT_ROTATION, DAMPED_TRACK, STRETCH_TO, COPY_LOCATION, TRACK_TO
bpy.ops.object.mode_set(mode='OBJECT')
5. Fotogramas clave en poses de huesos
import bpy, math
arm_obj = bpy.data.objects["Rig"]
bpy.context.view_layer.objects.active = arm_obj
bpy.ops.object.mode_set(mode='POSE')
if not arm_obj.animation_data:
arm_obj.animation_data_create()
action = bpy.data.actions.new("WalkCycle")
arm_obj.animation_data.action = action
# Fotogramas clave para balanceo del muslo: atrás → neutral → adelante
muslo = arm_obj.pose.bones["Thigh.L"]
for angle, frame in [(-30, 1), (0, 13), (30, 25)]:
muslo.rotation_euler = (math.radians(angle), 0, 0)
muslo.keyframe_insert(data_path="rotation_euler", frame=frame)
bpy.ops.object.mode_set(mode='OBJECT')
6. Crear y animar shape keys
import bpy
obj = bpy.data.objects["Head"]
mesh = obj.data
if not mesh.shape_keys: # Primero se requiere una clave "Basis"
obj.shape_key_add(name="Basis", from_mix=False)
sonrisa = obj.shape_key_add(name="Smile", from_mix=False)
for i, vert in enumerate(sonrisa.data):
if i in [42, 43, 56, 57]: # vértices de las comisuras
vert.co.z += 0.02
# Animar el valor de la shape key (0.0 → 1.0 → 0.0)
sk = mesh.shape_keys.key_blocks["Smile"]
for val, frame in [(0.0, 1), (1.0, 15), (0.0, 30)]:
sk.value = val
sk.keyframe_insert(data_path="value", frame=frame)
7. Superponer acciones con el editor NLA
import bpy
arm_obj = bpy.data.objects["Rig"]
if not arm_obj.animation_data:
arm_obj.animation_data_create()
# Insertar acciones como strips NLA en pistas separadas
pista1 = arm_obj.animation_data.nla_tracks.new()
pista1.name = "Walk"
strip1 = pista1.strips.new("Walk", start=1, action=bpy.data.actions["WalkCycle"])
strip1.repeat = 4 # repetir 4 veces
strip1.blend_type = 'REPLACE' # REPLACE, COMBINE, ADD, SUBTRACT, MULTIPLY
pista2 = arm_obj.animation_data.nla_tracks.new()
pista2.name = "Wave"
strip2 = pista2.strips.new("Wave", start=25, action=bpy.data.actions["WaveHand"])
strip2.blend_type = 'COMBINE' # mezclar sobre la caminata
strip2.influence = 0.8 # mezcla parcial
arm_obj.animation_data.action = None # limpiar acción activa para que NLA tome el control
8. Agregar drivers para animación basada en expresiones
import bpy
driver = bpy.data.objects["Cube"].driver_add("location", 2).driver # controla ubicación Z
driver.type = 'SCRIPTED'
driver.expression = "sin(frame * 0.1) * 2"
# Agregar una variable que lee la transformación de otro objeto
var = driver.variables.new()
var.name = "ctrl"
var.type = 'TRANSFORMS'
var.targets[0].id = bpy.data.objects["Controller"]
var.targets[0].transform_type = 'LOC_X'
var.targets[0].transform_space = 'WORLD_SPACE'
driver.expression = "ctrl * 3" # también funciona en shape keys mediante sk.driver_add("value")
Ejemplos
Ejemplo 1: Pelota rebotando con estiramiento y compresión (squash and stretch)
Solicitud del usuario: "Animar una pelota rebotando con squash and stretch"
import bpy
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.5, location=(0, 0, 3))
bola = bpy.context.active_object
bola.name = "BouncingBall"
fotogramas = [ # (fotograma, pos_z, escala_x, escala_y, escala_z)
(1, 3.0, 1.0, 1.0, 1.0), (12, 0.5, 1.0, 1.0, 1.0), # caída
(15, 0.3, 1.3, 1.3, 0.6), (18, 0.5, 0.85, 0.85, 1.2), # aplanar + estirar
(30, 2.2, 1.0, 1.0, 1.0), (42, 0.5, 1.0, 1.0, 1.0), # ápice + segunda caída
(45, 0.3, 1.2, 1.2, 0.7), (55, 1.5, 1.0, 1.0, 1.0), # rebote menor
(62, 0.5, 1.0, 1.0, 1.0), # reposo
]
for frame, z, sx, sy, sz in fotogramas:
bola.location = (0, 0, z)
bola.keyframe_insert(data_path="location", frame=frame)
bola.scale = (sx, sy, sz)
bola.keyframe_insert(data_path="scale", frame=frame)
for fc in bola.animation_data.action.fcurves:
for kp in fc.keyframe_points:
kp.interpolation = 'BEZIER'
bpy.context.scene.frame_end = 62
bpy.ops.wm.save_as_mainfile(filepath="/tmp/bouncing_ball.blend")
Ejemplo 2: Brazo con IK alcanzando un objeto
Solicitud del usuario: "Crear un brazo simple con IK y animarlo para que alcance un cubo"
import bpy
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
datos_brazo = bpy.data.armatures.new("ArmRig")
objeto_brazo = bpy.data.objects.new("ArmRig", datos_brazo)
bpy.context.collection.objects.link(objeto_brazo)
bpy.context.view_layer.objects.active = objeto_brazo
bpy.ops.object.mode_set(mode='EDIT')
anterior = None
for nombre, cabeza, cola in [("UpperArm",(0,0,1.5),(0.6,0,1.5)),
("Forearm",(0.6,0,1.5),(1.2,0,1.5)),
("Hand",(1.2,0,1.5),(1.4,0,1.5))]:
b = datos_brazo.edit_bones.new(nombre)
b.head, b.tail = cabeza, cola
if anterior: b.parent, b.use_connect = anterior, True
anterior = b
bpy.ops.object.mode_set(mode='OBJECT')
# Objetivo IK + constraint
bpy.ops.object.empty_add(type='PLAIN_AXES', location=(1.2, 0, 1.5))
objetivo_ik = bpy.context.active_object
objetivo_ik.name = "IK_Hand"
bpy.context.view_layer.objects.active = objeto_brazo
bpy.ops.object.mode_set(mode='POSE')
ik = objeto_brazo.pose.bones["Hand"].constraints.new('IK')
ik.target, ik.chain_count = objetivo_ik, 3
bpy.ops.object.mode_set(mode='OBJECT')
# Animar el objetivo IK para que alcance un cubo
bpy.ops.mesh.primitive_cube_add(size=0.3, location=(1.5, 0.5, 1.0))
for loc, frame in [((1.2,0,1.5),1), ((1.5,0.5,1.0),30), ((1.5,0.5,1.3),50)]:
objetivo_ik.location = loc
objetivo_ik.keyframe_insert(data_path="location", frame=frame)
for fc in objetivo_ik.animation_data.action.fcurves:
for kp in fc.keyframe_points:
kp.interpolation, kp.easing = 'BEZIER', 'EASE_IN_OUT'
bpy.context.scene.frame_end = 50
bpy.ops.wm.save_as_mainfile(filepath="/tmp/arm_grab.blend")
Pautas
data_pathdebe coincidir exactamente con la ruta RNA:"location","rotation_euler","scale",'["custom_prop"]'.- Flujo de trabajo de armaduras: Modo Edición para huesos (
edit_bones), Modo Pose para constraints y fotogramas clave (pose.bones). - Para IK, usar objetos Empty como objetivos.
chain_count=0resuelve toda la cadena hasta la raíz. - Las shape keys necesitan primero una clave "Basis". Se animan mediante
key_blocks["Name"].value(0.0 a 1.0). - Interpolación:
CONSTANTpara mantener/paso,LINEARpara movimiento mecánico,BEZIERcon easing para movimiento orgánico. - Configurar
animation_data.action = Nonepara que las strips NLA tomen el control; una acción activa sobrescribe NLA. - Para ciclos de caminata, animar un solo paso con fotogramas clave y usar un modificador de F-Curve Cycles o repetición NLA para bucle.
- Hornear (bake) constraints y drivers con
bpy.ops.nla.bake()antes de exportar; otros programas no pueden leerlos.