Claro! O erro NameError: name 'distance' is not defined indica que a variável distance está sendo usada antes de ser declarada ou importada.
Vou montar o script completo, corrigido e organizado, incluindo:
- Definição prévia de todas as variáveis usadas (
distance, num_cylinders, etc)
- Seu código de animação
- O cenário com chão e paredes em volta
- Iluminação infinita (SUN + ambiente)
- Materiais coloridos para chão, paredes, cilindros e martelo
- Limpeza correta dos objetos antigos para rodar várias vezes sem acumular lixo
Script completo, direto para rodar no Blender (UPBGE):
import bpy
import bmesh
from mathutils import Vector
from math import radians
# --- Parâmetros da animação e cena ---
num_cylinders = 10
distance = 3
total_frames = 500 # ampliado para conter ida + volta
frames_per_impact = 7 # intervalo entre impactos na animação
impact_duration = 15 # duração do "afundar"
z_scale_min = 0.2 # escala mínima no Z
impact_start_frame = 20 # frame em que martelo bate no primeiro cilindro
# --- Limpar objetos antigos relativos ---
objs_to_remove = [obj for obj in bpy.data.objects if (
obj.name.startswith("Cylinder") or
obj.name == "Martelo" or
obj.name in {
"Ground", "WallFront", "WallBack", "WallLeft", "WallRight",
"SunLight"
})]
for obj in objs_to_remove:
bpy.data.objects.remove(obj, do_unlink=True)
# --- Função para adicionar cilindros com origem na base ---
def add_cylinder_with_base_origin(radius=1, depth=2, location=(0,0,0), name="Cylinder"):
bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=location)
obj = bpy.context.object
obj.name = name
bpy.ops.object.mode_set(mode='OBJECT')
bpy.context.view_layer.objects.active = obj
obj.location.z += depth / 2
bpy.ops.object.transform_apply(location=True, rotation=False, scale=False)
return obj
# Criar cilindros
cylinders = []
for i in range(num_cylinders):
pos = (i*distance, 0, 0)
c = add_cylinder_with_base_origin(radius=1, depth=2, location=pos, name=f"Cylinder.{str(i+1).zfill(3)}")
cylinders.append(c)
if c.animation_data:
c.animation_data_clear()
# Criar martelo (cubo)
bpy.ops.mesh.primitive_cube_add(size=1.5, location=(-distance, 0, 1.5))
martelo = bpy.context.object
martelo.name = "Martelo"
if martelo.animation_data:
martelo.animation_data_clear()
# Animação do martelo
hammer_back_frame = impact_start_frame - 10
martelo.location = (-distance, 0, 1.5)
martelo.keyframe_insert(data_path="location", frame=hammer_back_frame)
martelo.rotation_euler = (0, 0, 0)
martelo.keyframe_insert(data_path="rotation_euler", frame=hammer_back_frame)
martelo.location = (0, 0, 1.5)
martelo.keyframe_insert(data_path="location", frame=impact_start_frame)
martelo.rotation_euler = (0, 0, 0)
martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame)
martelo.location = (-distance, 0, 1.5)
martelo.keyframe_insert(data_path="location", frame=impact_start_frame + 15)
martelo.rotation_euler = (0, 0, 0)
martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame + 15)
# Função para animar o efeito de "afundar"
def animate_sink(obj, start_frame, duration, scale_min):
obj.scale = (1, 1, 1)
obj.keyframe_insert(data_path="scale", frame=start_frame)
peak_frame = start_frame + duration // 2
obj.scale = (1, 1, scale_min)
obj.keyframe_insert(data_path="scale", frame=peak_frame)
end_frame = start_frame + duration
obj.scale = (1, 1, 1)
obj.keyframe_insert(data_path="scale", frame=end_frame)
# Animação ida (primeiro ao último cilindro)
for i, c in enumerate(cylinders):
start = impact_start_frame + i * frames_per_impact
animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
# Animação volta (último ao primeiro após pausa)
ida_end_frame = impact_start_frame + (num_cylinders - 1) * frames_per_impact + impact_duration
volta_start_delay = -7
for i, c in enumerate(reversed(cylinders)):
start = ida_end_frame + volta_start_delay + i * frames_per_impact
animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
# Ajustar timeline
scene = bpy.context.scene
scene.frame_start = 1
scene.frame_end = ida_end_frame + volta_start_delay + (num_cylinders - 1) * frames_per_impact + impact_duration + 20
print("Animação criada com ida e volta do efeito afundar!")
# --- Cenário: chão com paredes em volta ---
floor_size = distance * (num_cylinders - 1) + 20 # tamanho do chão
wall_height = 15
wall_thickness = 0.5
center_x = distance * (num_cylinders - 1) / 2
center_y = 0
# Chão
bpy.ops.mesh.primitive_plane_add(size=floor_size, location=(center_x, center_y, 0))
ground = bpy.context.object
ground.name = "Ground"
# Material chão cinza claro
mat_ground = bpy.data.materials.new(name="GroundMaterial")
mat_ground.use_nodes = True
bsdf = mat_ground.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (0.88, 0.88, 0.88, 1)
bsdf.inputs["Roughness"].default_value = 0.6
ground.data.materials.append(mat_ground)
# Função para criar parede
def create_wall(name, location, scale, rotation=(0,0,0), color=(1,1,1,1)):
bpy.ops.mesh.primitive_cube_add(location=location, scale=scale)
wall = bpy.context.object
wall.name = name
wall.rotation_euler = rotation
mat = bpy.data.materials.new(name=name+"Mat")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = color
bsdf.inputs["Roughness"].default_value = 0.3
if len(wall.data.materials):
wall.data.materials[0] = mat
else:
wall.data.materials.append(mat)
return wall
half_floor = floor_size / 2
# Paredes
wall_color = (0.95, 0.95, 0.95, 1)
wall_back = create_wall(
"WallBack",
location=(center_x, center_y - half_floor, wall_height/2),
scale=(half_floor, wall_thickness, wall_height),
color=wall_color
)
wall_front = create_wall(
"WallFront",
location=(center_x, center_y + half_floor, wall_height/2),
scale=(half_floor, wall_thickness, wall_height),
color=wall_color
)
wall_left = create_wall(
"WallLeft",
location=(center_x - half_floor, center_y, wall_height/2),
scale=(wall_thickness, half_floor, wall_height),
color=wall_color
)
wall_right = create_wall(
"WallRight",
location=(center_x + half_floor, center_y, wall_height/2),
scale=(wall_thickness, half_floor, wall_height),
color=wall_color
)
# --- Materiais coloridos para cilindros ---
for i, c in enumerate(cylinders):
mat = bpy.data.materials.new(name=f"CylinderMat.{i+1}")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
col_r = 0.1 + i * 0.05
col_g = 0.4 + i * 0.04
col_b = 0.7 - i * 0.03
bsdf.inputs["Base Color"].default_value = (col_r, col_g, col_b, 1)
bsdf.inputs["Roughness"].default_value = 0.25
if len(c.data.materials):
c.data.materials[0] = mat
else:
c.data.materials.append(mat)
# Material martelo vermelho vibrante
mat_martelo = bpy.data.materials.new(name="MarteloMaterial")
mat_martelo.use_nodes = True
bsdf = mat_martelo.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (1, 0.1, 0.1, 1)
bsdf.inputs["Metallic"].default_value = 0.3
bsdf.inputs["Roughness"].default_value = 0.2
martelo.data.materials.append(mat_martelo)
# --- Iluminação Infinita ---
# Luz do tipo SUN
bpy.ops.object.light_add(type='SUN', location=(0, 0, 50))
sun_light = bpy.context.object
sun_light.name = "SunLight"
sun_light.data.energy = 5.0
# Direcionar a luz para baixo em ângulo inclinado para melhor iluminação
sun_light.rotation_euler = (radians(-45), radians(0), radians(45))
# Luz ambiente através do World
world = bpy.context.scene.world
if not world:
world = bpy.data.worlds.new("World")
bpy.context.scene.world = world
world.use_nodes = True
nodes = world.node_tree.nodes
bg = nodes.get("Background")
if bg:
bg.inputs[0].default_value = (0.75, 0.75, 0.75, 1) # cor clara
bg.inputs[1].default_value = 1.2 # intensidade ambiente
print("Cenário completo criado com chão, paredes, animação e iluminação infinita.")
Como usar
- Abra o Blender/UPBGE.
- No editor de texto crie um novo texto e cole todo este código.
- Execute o script.
- Veja a animação criada automaticamente com o cenário, paredes, iluminação e materiais.
Se aparecer algum problema ou quiser adicionar algo, só avisar!