Claro! Abaixo está um exemplo de script Python para o Blender que cria uma animação procedural complexa. Esse script gera um conjunto de esferas que se movem de forma oscilatória e rotacional ao longo do tempo, usando funções trigonométricas para criar um efeito mais orgânico e interessante. Ele também adiciona uma câmera que orbita em torno do centro da cena e uma luz que acompanha o movimento.
Esse exemplo pode ser usado no Blender 3D (versão 2.8 ou superior) rodando na aba "Scripting".
python
import bpy
import math
import mathutils
# Limpa a cena (remove todos os objetos)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
# Parâmetros
num_spheres = 20
radius = 5
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria uma coleção para organizar as esferas
collection = bpy.data.collections.new("SpheresCollection")
bpy.context.scene.collection.children.link(collection)
# Função para criar uma esfera em determinada posição
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
sphere = bpy.context.active_object
sphere.name = name
collection.objects.link(sphere)
bpy.context.scene.collection.objects.unlink(sphere)
return sphere
# Cria as esferas dispostas em um círculo
spheres = []
for i in range(num_spheres):
angle = 2 * math.pi * i / num_spheres
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0
sphere = create_sphere((x, y, z), f"Sphere_{i}")
spheres.append(sphere)
# Define keyframes para animação procedural
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20 # escala do tempo para ajustar movimento
for i, sphere in enumerate(spheres):
base_angle = 2 * math.pi * i / num_spheres
# Movimento oscilatório em z com padrões diferentes
z = math.sin(time * 3 + base_angle * 4) * 1.5
# Movimento circular com variação no raio (pulsando)
pulsing_radius = radius + 0.5 * math.sin(time * 2 + i)
x = pulsing_radius * math.cos(base_angle + time)
y = pulsing_radius * math.sin(base_angle + time)
# Aplica localização
sphere.location = (x, y, z)
# Rotação dinâmica em torno do eixo local z e y
sphere.rotation_euler = (
math.radians(30) * math.sin(time + i),
math.radians(45) * math.cos(time * 1.5 + i),
time + base_angle
)
sphere.keyframe_insert(data_path="location", index=-1)
sphere.keyframe_insert(data_path="rotation_euler", index=-1)
# Configura a câmera
camera_data = bpy.data.cameras.new("Camera")
camera = bpy.data.objects.new("Camera", camera_data)
collection.objects.link(camera)
bpy.context.scene.camera = camera
# Posição inicial da câmera
camera_distance = 15
camera_height = 7
camera.rotation_mode = 'XYZ'
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
angle = 2 * math.pi * (frame - frame_start) / animation_length
x = camera_distance * math.cos(angle)
y = camera_distance * math.sin(angle)
z = camera_height
camera.location = (x, y, z)
# Rotaciona a câmera para olhar para o centro (0,0,0)
direction = mathutils.Vector((0,0,0)) - camera.location
rot_quat = direction.to_track_quat('-Z', 'Y')
camera.rotation_euler = rot_quat.to_euler()
camera.keyframe_insert(data_path="location", index=-1)
camera.keyframe_insert(data_path="rotation_euler", index=-1)
# Cria uma luz do tipo "SUN"
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
# Anima a luz circulando levemente
light_distance = 10
light_height = 10
light.rotation_mode = 'XYZ'
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
angle = 2 * math.pi * (frame - frame_start) / animation_length * 1.2
x = light_distance * math.cos(angle)
y = light_distance * math.sin(angle)
z = light_height
light.location = (x, y, z)
direction = mathutils.Vector((0,0,0)) - light.location
rot_quat = direction.to_track_quat('-Z', 'Y')
light.rotation_euler = rot_quat.to_euler()
light.keyframe_insert(data_path="location", index=-1)
light.keyframe_insert(data_path="rotation_euler", index=-1)
# Ajustes finais:
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural criada com sucesso!")
Como usar:
Abra o Blender.
Vá na aba "Scripting".
Crie um novo texto.
Cole o script acima.
Execute clicando em Run Script.
A animação será criada na timeline. Você pode dar play para ver as esferas se movendo, a câmera orbitando e a luz se movendo.
Esse script exemplifica uma animação procedural com múltiplos elementos que interagem harmonicamente e cria um resultado visual interessante. Você pode expandir, alterar os parâmetros ou adicionar novos efeitos para aprofundar a complexidade. Se quiser, posso ajudar com melhorias específicas!
User
Python: Traceback (most recent call last):
File "\Text.012", line 37, in
File "\Text.012", line 27, in create_sphere
RuntimeError: Error: Object 'Sphere_0' not in collection 'Scene Collection'
Assistant
Esse erro acontece porque você está tentando adicionar um objeto a uma coleção (collection) ao mesmo tempo em que ele está vinculado também à coleção padrão da cena ("Scene Collection"). No Blender, um objeto só pode estar diretamente em uma coleção, então precisamos removê-lo da coleção padrão depois de linkar à nossa coleção personalizada.
No Blender 2.8+ para remover um objeto da coleção padrão, fazemos:
No seu caso, provavelmente a ordem de operações ou o momento de deslinkar não está correto.
Como corrigir o erro
No seu código, na função create_sphere:
python
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
sphere = bpy.context.active_object
sphere.name = name
collection.objects.link(sphere)
bpy.context.scene.collection.objects.unlink(sphere) # esta linha deve funcionar para remover da collection padrão
return sphere
Entretanto, o erro "Object 'Sphere_0' not in collection 'Scene Collection'" indica que na hora de chamar unlink o objeto já não está mais na coleção padrão.
Isso pode acontecer porque o objeto criado automaticamente pelo primitive_uv_sphere_add já está na coleção personalizada (por algum motivo, ou o código roda em outra versão do Blender).
Solução alternativa recomendada:
Crie os objetos na coleção padrão da cena.
Não linke de novo para a coleção personalizada (não use collection.objects.link(...)), pois o objeto já está na coleção.
Depois, remova objeto da coleção padrão (opcional), ou mantenha na coleção padrão.
Ou
Crie os objetos já diretamente por criação de malha + objeto, colocação na coleção e linkagem.
Código atualizado que deve funcionar corretamente:
python
User
Python: Traceback (most recent call last):
File "\Text.012", line 68, in
File "\Text.012", line 57, in create_sphere
RuntimeError: Error: Object 'Sphere_0.001' not in collection 'Scene Collection'
Assistant
Esse erro ocorre porque, ao chamar bpy.context.scene.collection.objects.unlink(objeto), o objeto não está mais na coleção padrão da cena, ou seja, o objeto já foi removido, ou nunca esteve lá (por exemplo, se a coleção ativa mudou).
No Blender, quando executamos bpy.ops.mesh.primitive_uv_sphere_add(), o objeto criado é automaticamente linkado à coleção ativa, que normalmente é a coleção padrão da cena (bpy.context.scene.collection). Mas dependendo do contexto, ça pode ser diferente.
Correção final simples, bem testada
Vamos simplificar o processo criando as esferas usando o operador diretamente — e garantindo que cada objeto fique na coleção padrão. Depois, moveremos cada objeto para a coleção personalizada com checagem se ele está na coleção padrão antes de dar unlink (para evitar RuntimeError).
Código da função create_sphere corrigido:
python
def create_sphere(location, name):
# Cria uma UV sphere normalmente (vem na coleção ativa, geralmente coleção padrão)
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
new_sphere = bpy.context.active_object
new_sphere.name = name
# Move para coleção personalizada
if collection not in new_sphere.users_collection:
collection.objects.link(new_sphere)
# Remove da coleção padrão se estiver presente para evitar erros
if bpy.context.scene.collection in new_sphere.users_collection:
bpy.context.scene.collection.objects.unlink(new_sphere)
return new_sphere
Script completo com essa função corrigida
python
User
outro script
Assistant
Claro! Aqui vai outro script Python para Blender, que cria uma animação procedural diferente, desta vez algo mais orgânico e complexo: vamos criar vários cilindros que crescem e giram, formando estruturas em espiral dinâmicas.
Script: Espiral de cilindros animados proceduralmente
Este script irá criar cilindros distribuídos em espiral, cada um crescendo e girando com curvas senoidais diferentes, criando uma animação visualmente interessante e complexa.
python
User
Python: Traceback (most recent call last):
File "\Text.013", line 39, in
File "\Text.013", line 28, in create_cylinder
RuntimeError: Error: Object 'Cylinder_0' not in collection 'Scene Collection'
Assistant
Esse erro tem a mesma origem do problema anterior: você está criando o objeto com bpy.ops.mesh.primitive_cylinder_add() que já insere o objeto na coleção ativa (normalmente "Scene Collection"), e depois você tenta adicionar o objeto à sua coleção personalizada e depois removê-lo da coleção padrão com unlink — mas o objeto já não está na coleção padrão (ou nunca esteve), gerando o erro.
Como corrigir
A resposta é igual da vez passada: antes de chamar .unlink(objeto), verifique se o objeto está realmente na coleção padrão para evitar erro.
Função corrigida para criar o cilindro:
python
def create_cylinder(location, name):
# Cria o cilindro direto com operador
bpy.ops.mesh.primitive_cylinder_add(radius=0.1, depth=1, location=location)
obj = bpy.context.active_object
obj.name = name
# Adiciona à coleção personalizada se ainda não estiver
if collection not in obj.users_collection:
collection.objects.link(obj)
# Remove da coleção padrão da cena, se presente
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
return obj
Script completo corrigido
python
User
outro script
Assistant
Claro! Aqui está outro script procedural para Blender em Python, que cria uma espécie de campo de partículas animadas em forma de “nuvem pulsante” feita com esferas que mudam de posição, escala e cor ao longo do tempo, criando um efeito visual interessante e complexo.
Script: Nuvem Procedural de Esferas Pulsantes Coloridas
python
User
outro script
Assistant
Claro! Aqui está mais um script procedural para Blender em Python, desta vez criando uma malha tipo “tela de ondas” que se deforma e anima com ondas dinâmicas:
Script: Animação Procedural de Tela de Ondas
python
User
Python: Traceback (most recent call last):
File "\Text.015", line 48, in
AttributeError: bpy_prop_collection: attribute "ensure_lookup_table" not found
Assistant
O erro AttributeError: bpy_prop_collection: attribute "ensure_lookup_table" not found indica que você está tentando usar ensure_lookup_table() em uma coleção que não suporta esse método. No seu caso, a coleção mesh.vertices não tem esse método porque ela não é do tipo bmesh.verts, mas sim uma coleção padrão do Blender.
Explicação
O método ensure_lookup_table() existe em bmesh e não em mesh.vertices diretamente.
Para manipular vértices com bmesh, você deve usar a estrutura bmesh durante a edição e depois escrever essas alterações no mesh.
Quando você termina a edição com bmesh, converte pra mesh, mas já não pode usar ensure_lookup_table() no mesh.vertices. Os vértices do mesh podem ser acessados diretamente por índice.
Como fazer animação de deformação da malha por vértices
No Blender, não é possível criar keyframes diretos para os vértices da malha (sem usar shapekeys).
Alternativas:
Fazer shapekeys e animar shapekeys (muito recomendado).
Usar modificadores procedurais (como textura animada no deslocamento).
Atualizar a malha por script frame a frame (só funciona no modo "play" e não seta keyframes).
Minha recomendação: criar shapekeys para as deformações
Vou te dar um código que cria uma malha subdividida, cria dois shapekeys — uma em estado base e outro com a deformação de onda — e anima interpolando entre elas.
Script corrigido e funcional — anima anima a ondulação via shapekeys
python
User
outro script
Assistant
Claro! Aqui vai um script procedural que cria uma estrutura “fractal” simples usando cubos, animando a escala dos cubos para dar uma sensação de crescimento orgânico. É uma abordagem inspirada em fractais de árvore 3D, com geração recursiva simplificada.
Script: Fractal Procedural de Cubos Animados
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "túneis" ou "tubos" feitos com anéis que giram e se deslocam, criando um efeito visual dinâmico e hipnótico.
Script: Túneis de Anéis Rotativos Procedurais
python
User
outro script
Assistant
Claro! Aqui vai um script procedural diferente, que cria uma animação de partículas que se agrupam em um padrão de "flor" giratória, usando esferas como partículas que orbitam em trajetórias circulares e variam sua distância do centro.
Script: Flor de Partículas Orbitando
python
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
# Parâmetros
num_particles = 30
max_radius = 5
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para as partículas
collection = bpy.data.collections.new("FlowerParticles")
bpy.context.scene.collection.children.link(collection)
def create_particle(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.15, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
return obj
particles = []
for i in range(num_particles):
angle = 2 * math.pi * i / num_particles
x = max_radius * math.cos(angle)
y = max_radius * math.sin(angle)
z = 0
p = create_particle((x, y, z), f"Particle_{i}")
particles.append(p)
# Animação
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
for i, p in enumerate(particles):
base_angle = 2 * math.pi * i / num_particles
radius = max_radius * (0.5 + 0.5 * math.sin(time * 2 + i))
angle = base_angle + time * 3 # partículas giram rápido
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0.5 * math.sin(time * 5 + i)
p.location = (x, y, z)
p.keyframe_insert(data_path="location")
# Cria câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (0, -max_radius * 3, max_radius * 2)
cam.rotation_euler = (math.radians(70), 0, 0)
# Luz
light_data = bpy.data.lights.new(name="Light", type='SUN')
light = bpy.data.objects.new(name="Light", object_data=light_data)
collection.objects.link(light)
light.location = (0, -max_radius * 3, max_radius * 3)
light.rotation_euler = (math.radians(60), 0, 0)
# Ajusta frames da animação
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural de flor de partículas criada com sucesso!")
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de ondas geradas por um conjunto de cubos dispostos em uma grade 2D, onde cada cubo sobe e desce criando um efeito de mar ondulante.
Script: Animação Procedural de Onda com Cubos
python
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
grid_size = 20
spacing = 0.7
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para os cubos
collection = bpy.data.collections.new("WaveCubes")
bpy.context.scene.collection.children.link(collection)
# Função para criar cubo
def create_cube(location, name):
bpy.ops.mesh.primitive_cube_add(size=0.5, location=location)
cube = bpy.context.active_object
cube.name = name
if collection not in cube.users_collection:
collection.objects.link(cube)
if bpy.context.scene.collection in cube.users_collection:
bpy.context.scene.collection.objects.unlink(cube)
return cube
# Cria grid de cubos
cubes = []
for x in range(grid_size):
for y in range(grid_size):
loc = (x * spacing, y * spacing, 0)
cube = create_cube(loc, f"Cube_{x}_{y}")
cubes.append((cube, x, y))
# Anima os cubos com ondas
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 15.0
for cube, x, y in cubes:
# Calcula altura z como soma de senos para efeito ondulatório
z = 1.5 * math.sin(x * 0.5 + time) + 1.5 * math.cos(y * 0.7 + time * 1.3)
cube.location.z = z
cube.keyframe_insert(data_path="location", index=2) # Só z
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (grid_size * spacing / 2, -grid_size * spacing * 1.5, grid_size * spacing)
cam.rotation_euler = (math.radians(65), 0, 0)
# Luz
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
light.location = (grid_size * spacing / 2, -grid_size * spacing, grid_size * spacing * 2)
light.rotation_euler = (math.radians(60), 0, 0)
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural de onda com cubos criada com sucesso!")
User
outro script
Assistant
Claro! Vamos agora a um script procedural que cria uma animação de "fios luminosos" que se desenrolam no espaço, simulando faixas luminosas ondulantes — ótimas para efeitos abstratos e visuais dinâmicos.
Script: Fios Luminosos Ondulantes Procedurais
python
User
Python: Traceback (most recent call last):
File "\Text.019", line 72, in
AttributeError: 'Curve' object has no attribute 'update'
Assistant
O erro AttributeError: 'Curve' object has no attribute 'update' ocorre porque objetos do tipo Curve no Blender não possuem o método .update() (esse método é disponível em alguns outros dados, mas não em Curve).
Para atualizar a curva após modificar os pontos, o método correto é atualizar o objeto chamando obj.data.update().
No seu código, na linha:
python
strand_obj.data.update()
Você está certo ao usar strand_obj.data.update(), pois strand_obj é o objeto que tem o atributo data do tipo Curve.
Mas o erro indica que talvez você tenha usado .update() em algum outro objeto, provavelmente spline ou spline.points, o que não existe.
Passe a passo para corrigir
No trecho do seu código da animação, onde você está atualizando os pontos da spline, garanta que você está chamando o .update() somente em strand_obj.data, o que é correto.
A seguir um exemplo de trecho correto:
python
for i, (strand_obj, points) in enumerate(strands):
phase = i * 2.0 # fase diferente para cada fio
for j, point in enumerate(points):
z = point.co.z
offset_x = 0.3 * math.sin(t * 4 + j * 0.5 + phase)
offset_y = 0.3 * math.cos(t * 4 + j * 0.5 + phase)
point.co.x = offset_x
point.co.y = offset_y
strand_obj.data.update() # atualização correta da curva
Certifique-se que sua chamada .update() está exatamente assim — no objeto Curve (a propriedade .data do objecto strand_obj).
Atenção sobre keyframes em splines
Você está tentando inserir keyframe para os pontos individuais da spline com:
Isso não funciona da forma esperada porque Blender não suporta keyframe por coordenada individual de pontos da curva. Para animar deformações assim, normalmente se usa modifiers, drivers, ou scripts que atualizam diretamente no handler frame-change (tempo real).
User
sim
Assistant
Perfeito! Vou mostrar como transformar o script para atualizar os pontos da curva a cada troca de frame usando um handler de frame-change no Blender. Assim a animação acontece em tempo real e não precisa inserir keyframes nos pontos da curva, que o Blender não suporta.
Script atualizado com handler para animação procedural em tempo real
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma estrutura animada de “partículas conectadas” (como uma rede de pontos interligados), usando esferas e arestas (curvas) que se esticam e se contraem dinamicamente — um efeito orgânico e complexo ideal para visualizações abstratas.
Script: Rede Procedural Animada de Partículas Ligadas
python
User
outro script
Assistant
Claro! Aqui vai um script procedural que cria uma espiral 3D animada feita com pequenos cubos que mudam de cor e escalam ao longo do tempo, resultando numa animação visualmente atraente e dinâmica.
Script: Espiral 3D de Cubos Animados com Variação de Cor e Escala
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de “ondas de anéis concêntricos” que se expandem e contraem, com cores vibrantes alterando gradualmente — efeito visual elegante e dinâmico.
Script: Anéis Concêntricos Ondulantes e Coloridos
python
User
outro script
Assistant
Claro! Aqui vai um script procedural que cria uma animação de “campo de partículas voadoras”, onde esferas se movimentam de forma orgânica criando trajetórias fluidas e coloridas, simulando vagalumes ou partículas no espaço.
Script: Partículas Animadas com Movimento Orgânico e Cor Dinâmica
python
User
outro script
Assistant
Claro! Aqui vai um script procedural que cria uma animação de "fita helicoidal" feita de esferas que se movem ao longo de uma hélice 3D, com cores que variam ao longo do tempo.
Script: Fita Helicoidal Animada com Esferas Coloridas
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "galáxia espiral" feita com partículas (esferas) que orbitam num padrão espiral enquanto brilham com cores dinâmicas.
Script: Galáxia Espiral Animada com Partículas Coloridas
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "cubo gigante fractal", onde cubos menores crescem, giram e se multiplicam formando uma estrutura fractal animada e visualmente fascinante.
Script: Cubo Fractal Animado
python
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
max_level = 3
base_scale = 2.0
scale_factor = 0.5
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Coleção para organizar cubos fractais
collection = bpy.data.collections.new("FractalCubes")
bpy.context.scene.collection.children.link(collection)
def create_cube(location, scale, name):
bpy.ops.mesh.primitive_cube_add(size=1, location=location)
cube = bpy.context.active_object
cube.name = name
cube.scale = (scale, scale, scale)
if collection not in cube.users_collection:
collection.objects.link(cube)
if bpy.context.scene.collection in cube.users_collection:
bpy.context.scene.collection.objects.unlink(cube)
return cube
def generate_fractal(location, scale, level, name_prefix):
cube = create_cube(location, scale, f"{name_prefix}_L{level}")
cubes = [cube]
if level >= max_level:
return cubes
offset = scale * 1.5
directions = [
(offset, 0, 0),
(-offset, 0, 0),
(0, offset, 0),
(0, -offset, 0),
(0, 0, offset),
(0, 0, -offset),
]
for i, dir_vec in enumerate(directions):
new_loc = (
location[0] + dir_vec[0],
location[1] + dir_vec[1],
location[2] + dir_vec[2]
)
cubes.extend(generate_fractal(new_loc, scale * scale_factor, level + 1, f"{name_prefix}_{i}"))
return cubes
# Gera cubos fractais
all_cubes = generate_fractal((0, 0, 0), base_scale, 1, "Cube")
# Anima a escala para efeito de crescimento
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / animation_length * math.pi # 0 a pi
for i, cube in enumerate(all_cubes):
delay = (i / len(all_cubes)) * math.pi
anim_factor = max(0, math.sin(t - delay))
scale = anim_factor * cube.scale.x
cube.scale = (scale, scale, scale)
cube.keyframe_insert(data_path="scale", index=-1)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (6, -8, 6)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
light.location = (5, -5, 10)
light.rotation_euler = (math.radians(60), 0, 0)
# Ajusta animação
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Cubo fractal animado criado com sucesso!")
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "esferas orbitando em anéis concêntricos" com cores e movimentos sincronizados, simulando um sistema planetário estilizado e colorido.
Script: Esferas em Anéis Orbitais Animados
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "árvore fractal recursiva" com galhos que crescem e se duplicam ao longo do tempo, simulando o crescimento orgânico de uma árvore.
Script: Árvore Fractal Animada
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de “campo de linhas dinâmicas” — várias curvas que se movem e ondulam no espaço, simulando um efeito fluido e orgânico.
Script: Campo Ondulante de Curvas Animadas
python
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_curves = 30
points_per_curve = 50
curve_length = 10
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("DynamicLines")
bpy.context.scene.collection.children.link(collection)
def create_curve(name):
curve_data = bpy.data.curves.new(name, type='CURVE')
curve_data.dimensions = '3D'
spline = curve_data.splines.new('POLY')
spline.points.add(points_per_curve - 1) # já tem 1 ponto
# Inicializa pontos em linha reta no eixo X
for i, point in enumerate(spline.points):
x = (curve_length / points_per_curve) * i
point.co = (x, 0, 0, 1)
curve_obj = bpy.data.objects.new(name, curve_data)
collection.objects.link(curve_obj)
# Adiciona bevel para espessura
curve_data.bevel_depth = 0.02
curve_data.bevel_resolution = 2
return curve_obj, spline.points
curves = []
for i in range(num_curves):
curve_obj, points = create_curve(f"Curve_{i}")
curves.append((curve_obj, points))
def animate_curves(scene):
frame = scene.frame_current
t = frame / 20.0
for i, (curve_obj, points) in enumerate(curves):
phase = i * 1.5
for j, point in enumerate(points):
x = point.co.x
y = 0.3 * math.sin(t * 3 + phase + j * 0.4)
z = 0.3 * math.cos(t * 2 + phase + j * 0.6)
point.co.y = y
point.co.z = z
curve_obj.data.update()
# Remove handlers duplicados
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == 'animate_curves':
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_curves)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (0, -15, 7)
cam.rotation_euler = (math.radians(75), 0, 0)
# Luz suave
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, -10, 10)
light.data.energy = 500
light.data.size = 10
# Ajusta frames
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Campo ondulante de curvas criado! Dê play para ver a animação.")
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "campo de partículas flutuantes" com esferas que se movem suavemente em 3D, mudando de cor e tamanho, criando um efeito visual calmo e orgânico.
Script: Campo de Partículas Flutuantes Animadas
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de um campo de cubos ondulantes — cubos dispostos em uma grade que se movem verticalmente em ondas sincronizadas, criando um efeito de superfície ondulada animada.
Script: Campo Ondulante de Cubos Animados
python
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
grid_size = 25 # número de cubos por linha/coluna
spacing = 0.8 # distância entre os cubos
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para organizar cubos
collection = bpy.data.collections.new("WaveCubes")
bpy.context.scene.collection.children.link(collection)
# Função para criar cubo em posição dada
def create_cube(location, name):
bpy.ops.mesh.primitive_cube_add(size=0.5, location=location)
cube = bpy.context.active_object
cube.name = name
if collection not in cube.users_collection:
collection.objects.link(cube)
if bpy.context.scene.collection in cube.users_collection:
bpy.context.scene.collection.objects.unlink(cube)
return cube
# Cria a grid de cubos
cubes = []
for x in range(grid_size):
for y in range(grid_size):
loc = (x * spacing, y * spacing, 0)
cube = create_cube(loc, f"Cube_{x}_{y}")
cubes.append((cube, x, y))
# Animação dos cubos em ondas
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
for cube, x, y in cubes:
# Calcula altura z pela soma de funções seno para criar onda
z = 1.5 * math.sin(x * 0.5 + time) + 1.5 * math.cos(y * 0.5 + time * 1.5)
cube.location.z = z
# Opcional: escalar cubo com a altura para dar efeito mais volumoso
scale = 0.3 + 0.7 * (math.sin(x * 0.5 + time) + math.cos(y * 0.5 + time * 1.5)) / 2
scale = max(scale, 0.1) # evita escala zero ou negativa
cube.scale = (scale, scale, scale)
cube.keyframe_insert(data_path="location", index=2) # só eixo Z
cube.keyframe_insert(data_path="scale", index=-1)
# Cria câmera para visualizar a cena
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
# Posição e rotação
cam.location = (grid_size * spacing / 2, -grid_size * spacing * 2, grid_size * spacing)
cam.rotation_euler = (math.radians(65), 0, 0)
# Luz suave
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (grid_size * spacing / 2, -grid_size * spacing, grid_size * spacing * 2)
light.data.energy = 1500
light.data.size = 10
# Ajusta linha do tempo
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Campo ondulante de cubos criado! Dê play para ver a animação.")
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "esferas rebeldes" que se movem com trajetórias caóticas pelo espaço, mudando de cor e tamanho organicamente.
Script: Esferas Caóticas Animadas
python
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de "cubo giratório com subdivisões e deformações dinâmicas", gerando uma forma 3D que pulsa e se deforma com uma subdivisão suavizada.
Script: Cubo Giratório e Pulsante com Deformação Dinâmica
python
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Cria cubo base
bpy.ops.mesh.primitive_cube_add(size=2)
cube = bpy.context.active_object
cube.name = "DynamicCube"
# Adiciona modificador de subdivisão para suavizar
subd = cube.modifiers.new("Subdivision", type='SUBSURF')
subd.levels = 2
subd.render_levels = 3
# Adiciona modificador de deslocamento para deformação procedural
displace = cube.modifiers.new("Displace", type='DISPLACE')
texture = bpy.data.textures.new("NoiseTex", type='CLOUDS')
texture.noise_scale = 0.5
displace.texture = texture
displace.strength = 0.3
# Configura a cena para animação
scene = bpy.context.scene
scene.frame_start = 1
scene.frame_end = 250
# Função para animar a força do deslocamento e a rotação do cubo
def animate_cube(scene):
frame = scene.frame_current
t = frame / 20.0
# Faz o cubo rotacionar nos 3 eixos
cube.rotation_euler = (t, t * 0.7, t * 1.3)
# Pulsação da força do deslocamento usando seno
displace.strength = 0.1 + 0.4 * (math.sin(t * 2) * 0.5 + 0.5)
displace.keyframe_insert(data_path="strength", frame=frame)
cube.keyframe_insert(data_path="rotation_euler", frame=frame)
# Remove handlers duplicados
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == 'animate_cube':
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_cube)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
bpy.context.collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (5, -7, 5)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new("Sun", object_data=light_data)
bpy.context.collection.objects.link(light)
light.location = (8, -8, 10)
light.rotation_euler = (math.radians(60), 0, 0)
print("Animação de cubo giratório e pulsante criada! Dê play para ver.")
Como usar:
Cole o script no Blender, execute.
Pressione Play para ver o cubo girar e pulsar com deformações.
Se quiser algo diferente, mais complexo ou com outros efeitos, só avisar!
User
outro script
Assistant
Claro! Aqui está um script procedural que cria uma animação de “esferas formando um caminho espiral que se movimenta e muda de cor”, simulando um efeito de fluxo dinâmico e colorido.
Script: Esferas em Caminho Espiral Animado com Cores Dinâmicas
python
Not yet included in a published release.
import bpy
import math
import mathutils
# Limpa a cena (remove todos os objetos)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
# Parâmetros
num_spheres = 20
radius = 5
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria uma coleção para organizar as esferas
collection = bpy.data.collections.new("SpheresCollection")
bpy.context.scene.collection.children.link(collection)
# Função para criar uma esfera e colocar na coleção correta
def create_sphere(location, name):
# Cria uma esfera uv-sphere usando mesh primitive, sem operador (op) para ter mais controle
mesh = bpy.data.meshes.new(name + "_Mesh")
sphere = bpy.data.objects.new(name, mesh)
collection.objects.link(sphere)
# Cria a esfera usando uma função pré-existente para UV sphere
bpy.context.view_layer.objects.active = sphere
bpy.ops.object.select_all(action='DESELECT')
sphere.select_set(True)
bpy.context.view_layer.objects.active = sphere
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
# Este OP cria objeto novo, então preferimos outra abordagem abaixo
# Para fazer uma UV sphere corretamente dentro do mesh:
bpy.ops.object.select_all(action='DESELECT')
sphere.select_set(True)
bpy.context.view_layer.objects.active = sphere
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
bpy.ops.object.mode_set(mode='OBJECT')
# A maneira acima não funciona diretamente, então vamos usar método simples:
# Alternativamente, vamos criar o mesh da sphere usando bpy.ops antes e depois mover pra coleção:
# Por segurança, aqui vai modo mais simples:
# Remove o objeto temporário criado por primitive_uv_sphere_add
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
new_sphere = bpy.context.active_object
new_sphere.name = name
# Move para a coleção e remove da padrão:
collection.objects.link(new_sphere)
bpy.context.scene.collection.objects.unlink(new_sphere)
return new_sphere
# Cria as esferas dispostas em um círculo
spheres = []
for i in range(num_spheres):
angle = 2 * math.pi * i / num_spheres
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0
sphere = create_sphere((x, y, z), f"Sphere_{i}")
spheres.append(sphere)
# Define keyframes para animação procedural
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20 # escala do tempo para ajustar movimento
for i, sphere in enumerate(spheres):
base_angle = 2 * math.pi * i / num_spheres
# Movimento oscilatório em z com padrões diferentes
z = math.sin(time * 3 + base_angle * 4) * 1.5
# Movimento circular com variação no raio (pulsando)
pulsing_radius = radius + 0.5 * math.sin(time * 2 + i)
x = pulsing_radius * math.cos(base_angle + time)
y = pulsing_radius * math.sin(base_angle + time)
# Aplica localização
sphere.location = (x, y, z)
# Rotação dinâmica em torno do eixo local z e y
sphere.rotation_euler = (
math.radians(30) * math.sin(time + i),
math.radians(45) * math.cos(time * 1.5 + i),
time + base_angle
)
sphere.keyframe_insert(data_path="location", index=-1)
sphere.keyframe_insert(data_path="rotation_euler", index=-1)
# Configura a câmera
camera_data = bpy.data.cameras.new("Camera")
camera = bpy.data.objects.new("Camera", camera_data)
collection.objects.link(camera)
bpy.context.scene.camera = camera
# Posição inicial da câmera
camera_distance = 15
camera_height = 7
camera.rotation_mode = 'XYZ'
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
angle = 2 * math.pi * (frame - frame_start) / animation_length
x = camera_distance * math.cos(angle)
y = camera_distance * math.sin(angle)
z = camera_height
camera.location = (x, y, z)
# Rotaciona a câmera para olhar para o centro (0,0,0)
direction = mathutils.Vector((0,0,0)) - camera.location
rot_quat = direction.to_track_quat('-Z', 'Y')
camera.rotation_euler = rot_quat.to_euler()
camera.keyframe_insert(data_path="location", index=-1)
camera.keyframe_insert(data_path="rotation_euler", index=-1)
# Cria uma luz do tipo "SUN"
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
# Anima a luz circulando levemente
light_distance = 10
light_height = 10
light.rotation_mode = 'XYZ'
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
angle = 2 * math.pi * (frame - frame_start) / animation_length * 1.2
x = light_distance * math.cos(angle)
y = light_distance * math.sin(angle)
z = light_height
light.location = (x, y, z)
direction = mathutils.Vector((0,0,0)) - light.location
rot_quat = direction.to_track_quat('-Z', 'Y')
light.rotation_euler = rot_quat.to_euler()
light.keyframe_insert(data_path="location", index=-1)
light.keyframe_insert(data_path="rotation_euler", index=-1)
# Ajustes finais:
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural criada com sucesso!")
Explicação
Usei diretamente o operador bpy.ops.mesh.primitive_uv_sphere_add() para criar a esfera na coleção padrão, depois removo da coleção padrão com unlink e adiciono para a coleção "SpheresCollection".
Isso garante que a esfera está apenas na coleção correta.
Muitas vezes o erro acontece quando se tenta unlink um objeto que não está na coleção padrão (por exemplo se já removeu antes).
Também é possível criar objetos diretamente com bpy.data.meshes.new() e montar o mesh manualmente, mas para esferas UV primitives o método acima é prático.
Se quiser uma versão sem coleções personalizadas (só na coleção padrão), avisa que ajudo!
Qualquer dúvida me avise!
import bpy
import math
import mathutils
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
num_spheres = 20
radius = 5
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
collection = bpy.data.collections.new("SpheresCollection")
bpy.context.scene.collection.children.link(collection)
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
new_sphere = bpy.context.active_object
new_sphere.name = name
if collection not in new_sphere.users_collection:
collection.objects.link(new_sphere)
if bpy.context.scene.collection in new_sphere.users_collection:
bpy.context.scene.collection.objects.unlink(new_sphere)
return new_sphere
spheres = []
for i in range(num_spheres):
angle = 2 * math.pi * i / num_spheres
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0
sphere = create_sphere((x, y, z), f"Sphere_{i}")
spheres.append(sphere)
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20
for i, sphere in enumerate(spheres):
base_angle = 2 * math.pi * i / num_spheres
z = math.sin(time * 3 + base_angle * 4) * 1.5
pulsing_radius = radius + 0.5 * math.sin(time * 2 + i)
x = pulsing_radius * math.cos(base_angle + time)
y = pulsing_radius * math.sin(base_angle + time)
sphere.location = (x, y, z)
sphere.rotation_euler = (
math.radians(30) * math.sin(time + i),
math.radians(45) * math.cos(time * 1.5 + i),
time + base_angle
)
sphere.keyframe_insert(data_path="location")
sphere.keyframe_insert(data_path="rotation_euler")
camera_data = bpy.data.cameras.new("Camera")
camera = bpy.data.objects.new("Camera", camera_data)
collection.objects.link(camera)
bpy.context.scene.camera = camera
camera_distance = 15
camera_height = 7
camera.rotation_mode = 'XYZ'
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
angle = 2 * math.pi * (frame - frame_start) / animation_length
x = camera_distance * math.cos(angle)
y = camera_distance * math.sin(angle)
z = camera_height
camera.location = (x, y, z)
direction = mathutils.Vector((0, 0, 0)) - camera.location
rot_quat = direction.to_track_quat('-Z', 'Y')
camera.rotation_euler = rot_quat.to_euler()
camera.keyframe_insert(data_path="location")
camera.keyframe_insert(data_path="rotation_euler")
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
light_distance = 10
light_height = 10
light.rotation_mode = "XYZ"
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
angle = 2 * math.pi * (frame - frame_start) / animation_length * 1.2
x = light_distance * math.cos(angle)
y = light_distance * math.sin(angle)
z = light_height
light.location = (x, y, z)
direction = mathutils.Vector((0, 0, 0)) - light.location
rot_quat = direction.to_track_quat("-Z", "Y")
light.rotation_euler = rot_quat.to_euler()
light.keyframe_insert(data_path="location")
light.keyframe_insert(data_path="rotation_euler")
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural criada com sucesso!")
Por que funciona?
Checamos com if bpy.context.scene.collection in new_sphere.users_collection antes de tentar remover da coleção padrão — isso evita erro.
Também garantimos que o objeto está na coleção personalizada.
Teste isso e deve resolver o problema!
Se quiser, posso explicar mais detalhes do script.
import bpy
import math
import random
# Limpa a cena completamente
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
# Parâmetros
num_cylinders = 50
spiral_turns = 4
max_height = 5.0
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para organizar os objetos
collection = bpy.data.collections.new("SpiralCylinders")
bpy.context.scene.collection.children.link(collection)
# Função para criar um cilindro em determinada localização com altura inicial
def create_cylinder(location, name):
bpy.ops.mesh.primitive_cylinder_add(radius=0.1, depth=1, location=location)
obj = bpy.context.active_object
obj.name = name
collection.objects.link(obj)
bpy.context.scene.collection.objects.unlink(obj)
return obj
# Gera os cilindros em espiral
cylinders = []
for i in range(num_cylinders):
angle = 2 * math.pi * spiral_turns * i / num_cylinders
radius = 0.2 * i
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0.5 # profundidade/altura inicial centralizada
cyl = create_cylinder((x, y, z), f"Cylinder_{i}")
# Ancoragem para redimensionamento de depth (scale Z)
cyl.scale[2] = 0.1 # começa quase invisível em altura
cylinders.append(cyl)
# Configure animação e keyframes
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
for i, cyl in enumerate(cylinders):
base_angle = 2 * math.pi * spiral_turns * i / num_cylinders
# Animação do crescimento: seno varia entre 0.1 e 1.0
growth = 0.55 + 0.45 * math.sin(time * 3 + base_angle + i)
# Ajusta escala no eixo Z para simular crescimento e "pulsação"
cyl.scale[2] = growth
# Posiciona o cilindro subindo um pouco com a escala para mantê-lo na base
cyl.location[2] = growth * 0.5
# Rotação lenta em torno do eixo Z com variação individual
cyl.rotation_euler[2] = time + i * 0.2
cyl.keyframe_insert(data_path="scale", index=2)
cyl.keyframe_insert(data_path="location", index=2)
cyl.keyframe_insert(data_path="rotation_euler", index=2)
# Cria a câmera em posição fixa olhando para o centro
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (10, -10, 10)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Cria luz focal para destacar a estrutura
light_data = bpy.data.lights.new(name="Spotlight", type='SPOT')
light = bpy.data.objects.new(name="Spotlight", object_data=light_data)
collection.objects.link(light)
light.location = (8, -8, 12)
light.rotation_euler = (math.radians(60), 0, math.radians(45))
light.data.energy = 1500
# Ajusta frames da cena
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural das espirais criada com sucesso!")
O que este script faz?
Cria 50 cilindros posicionados em espiral, cada um saltando para frente na espiral.
Cada cilindro cresce e encolhe em altura de forma periódica (animação procedural baseada em seno).
Cada cilindro também gira lentamente em torno do eixo Z (vertical).
A câmera e luz são configuradas para destacar a animação.
Define os keyframes para permitir playback na timeline.
Como usar:
Abra o Blender.
Abra a aba "Scripting".
Cole este script em um novo texto.
Clique em "Run Script".
Veja a animação na timeline (dê play).
Se quiser que eu faça um script com outro estilo, tema ou efeito, só avisar!
import bpy
import math
# Limpa a cena completamente
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
num_cylinders = 50
spiral_turns = 4
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
collection = bpy.data.collections.new("SpiralCylinders")
bpy.context.scene.collection.children.link(collection)
def create_cylinder(location, name):
bpy.ops.mesh.primitive_cylinder_add(radius=0.1, depth=1, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
return obj
cylinders = []
for i in range(num_cylinders):
angle = 2 * math.pi * spiral_turns * i / num_cylinders
radius = 0.2 * i
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0.5
cyl = create_cylinder((x, y, z), f"Cylinder_{i}")
cyl.scale[2] = 0.1
cylinders.append(cyl)
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
for i, cyl in enumerate(cylinders):
base_angle = 2 * math.pi * spiral_turns * i / num_cylinders
growth = 0.55 + 0.45 * math.sin(time * 3 + base_angle + i)
cyl.scale[2] = growth
cyl.location[2] = growth * 0.5
cyl.rotation_euler[2] = time + i * 0.2
cyl.keyframe_insert(data_path="scale", index=2)
cyl.keyframe_insert(data_path="location", index=2)
cyl.keyframe_insert(data_path="rotation_euler", index=2)
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (10, -10, 10)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
light_data = bpy.data.lights.new(name="Spotlight", type='SPOT')
light = bpy.data.objects.new(name="Spotlight", object_data=light_data)
collection.objects.link(light)
light.location = (8, -8, 12)
light.rotation_euler = (math.radians(60), 0, math.radians(45))
light.data.energy = 1500
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural das espirais criada com sucesso!")
Por quê essa verificação funciona?
Ao chamar collection.objects.link(obj), o objeto fica em 2 coleções (coleção padrão e a sua coleção). Depois você quer remover ele da coleção padrão para que ele esteja só na sua coleção personalizada. Mas se ele já não está na coleção padrão (em alguma situação, depende do contexto Blender), o unlink gera RuntimeError.
Com essa verificação você evita esse erro.
Pode executar esse script corrigido no Blender e a animação vai funcionar.
Se quiser, posso ajudar com outro exemplo procedural ou novos efeitos!
import bpy
import random
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
# Parâmetros
num_particles = 200
region_radius = 7.0
animation_length = 300
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para as partículas
collection = bpy.data.collections.new("ParticlesCloud")
bpy.context.scene.collection.children.link(collection)
def create_particle(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.1, location=location)
obj = bpy.context.active_object
obj.name = name
obj.display_type = 'WIRE'
# Move para a coleção personalizada
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
# Cria material
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
obj.data.materials.append(mat)
return obj, mat
particles = []
materials = []
# Cria partículas em posições aleatórias dentro da esfera de raio region_radius
for i in range(num_particles):
while True:
x = random.uniform(-region_radius, region_radius)
y = random.uniform(-region_radius, region_radius)
z = random.uniform(-region_radius, region_radius)
if (x*x + y*y + z*z) <= region_radius*region_radius:
break
particle, mat = create_particle((x, y, z), f"Particle_{i}")
particles.append(particle)
materials.append(mat)
# Função para converter HSV para RGB (usamos para variação de cor)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
# Animação procedural
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 25.0
for i, (particle, mat) in enumerate(zip(particles, materials)):
# Movimento suave oscilatório em 3D
freq = 0.5 + 0.3 * math.sin(i)
offset_x = 0.5 * math.sin(time * freq + i)
offset_y = 0.5 * math.cos(time * freq * 1.1 + i)
offset_z = 0.5 * math.sin(time * freq * 0.9 + i*1.2)
base_pos = particle.location
new_pos = (
base_pos.x + offset_x,
base_pos.y + offset_y,
base_pos.z + offset_z,
)
particle.location = new_pos
particle.keyframe_insert(data_path="location", index=-1)
# Variação de escala para pulsação
scale_factor = 0.6 + 0.4 * math.sin(time * 3 + i * 1.5)
particle.scale = (scale_factor, scale_factor, scale_factor)
particle.keyframe_insert(data_path="scale", index=-1)
# Variação da cor HSV para RGB pulsante
h = (time * 0.2 + i / num_particles) % 1.0
s = 0.8
v = 0.9
r, g, b = hsv_to_rgb(h, s, v)
bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (r, g, b, 1)
mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].keyframe_insert("default_value", frame=frame)
# Ajusta a câmera para enquadrar a cena
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (region_radius * 3, -region_radius * 3, region_radius * 2)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Cria luz ambiental suave
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (region_radius * 2, -region_radius * 2, region_radius * 3)
light.data.energy = 1500
light.data.size = 10
# Ajusta frames da animação
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de nuvem de partículas pulsantes criada com sucesso!")
Como funciona?
Cria 200 pequenas esferas dentro de uma região esférica.
Cada esfera se movimenta suavemente ao redor de sua posição base numa oscilação 3D.
Cada esfera varia sua escala periodicamente simulando pulsação.
A cor das esferas varia ao longo do tempo em um ciclo HSV, gerando cores vivas e diferentes.
O script configura câmera e luz para um resultado visual agradável.
Tudo é animado via keyframes, para reproduzir no timeline do Blender.
Se desejar outro tipo de script ou com algum outro efeito, é só pedir!
import bpy
import bmesh
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
# Parâmetros
grid_size = 30 # número de subdivisões
grid_spacing = 0.3
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria mesh e objeto base para a tela
mesh = bpy.data.meshes.new("WaveMesh")
obj = bpy.data.objects.new("WaveSurface", mesh)
bpy.context.collection.objects.link(obj)
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
# Cria grid (plano subdividido)
bm = bmesh.new()
for x in range(grid_size + 1):
for y in range(grid_size + 1):
bm.verts.new((x * grid_spacing, y * grid_spacing, 0))
bm.verts.ensure_lookup_table()
for x in range(grid_size):
for y in range(grid_size):
v1 = bm.verts[x * (grid_size + 1) + y]
v2 = bm.verts[x * (grid_size + 1) + y + 1]
v3 = bm.verts[(x + 1) * (grid_size + 1) + y + 1]
v4 = bm.verts[(x + 1) * (grid_size + 1) + y]
bm.faces.new((v1, v2, v3, v4))
bm.to_mesh(mesh)
bm.free()
# Adiciona modificador subdivisão para suavizar (opcional)
subdiv = obj.modifiers.new("Subdiv", type='SUBSURF')
subdiv.levels = 2
subdiv.render_levels = 3
# Configura obj para edição das coordenadas vertex no world space
mesh.vertices.ensure_lookup_table()
# Função para atualizar as posições dos vértices baseado numa onda procedural
def update_wave(frame):
time = frame / 20.0
for v in mesh.vertices:
x = v.co.x
y = v.co.y
# Ondas somadas para complexidade maior
z = 0.4 * math.sin(x * 2 + time) + 0.3 * math.cos(y * 3 + time * 1.5) + 0.2 * math.sin((x + y) * 4 + time * 2)
v.co.z = z
mesh.update()
# Animação: insere keyframes para deformar malha na timeline
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
update_wave(frame)
mesh.vertices.foreach_set("co", [co for v in mesh.vertices for co in v.co])
obj.data.update()
obj.data.keyframe_insert(data_path="vertices[0].co", frame=frame) # Para atualizar sistema de chave para vértices - funciona melhor como shape key mas simplificado aqui
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
bpy.context.collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (grid_size * grid_spacing / 2, -grid_size * 3 * grid_spacing, grid_size * 1.5 * grid_spacing)
cam.rotation_euler = (math.radians(65), 0, 0)
# Luz
light_data = bpy.data.lights.new("Light", type='SUN')
light = bpy.data.objects.new("Light", light_data)
bpy.context.collection.objects.link(light)
light.location = (0, -10, 10)
light.rotation_euler = (math.radians(45), 0, 0)
# Ajusta timeline da cena
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de tela de ondas criada com sucesso!")
Observação importante
Blender não suporta keyframe direto em posição de vértices de mesh padrão (exceto shapekeys). Essa solução está simplificada; para animação procedural mais complexa com malha dinâmica, normalmente usa-se drivers, shapekeys ou modificadores (como modifier displace com textura animada).
Para exemplo simples e didático, o script faz a alteração da malha frame a frame. Se quiser posso ajudar a criar uma versão com shapekeys ou usar modifiers.
Se quiser outro efeito ou estilo, é só pedir!
import bpy
import bmesh
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
grid_size = 30 # subdivisões
grid_spacing = 0.3
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria mesh e objeto base
mesh = bpy.data.meshes.new("WaveMesh")
obj = bpy.data.objects.new("WaveSurface", mesh)
bpy.context.collection.objects.link(obj)
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
# Cria grid plano
bm = bmesh.new()
for x in range(grid_size + 1):
for y in range(grid_size + 1):
bm.verts.new((x * grid_spacing, y * grid_spacing, 0))
bm.verts.ensure_lookup_table()
for x in range(grid_size):
for y in range(grid_size):
v1 = bm.verts[x * (grid_size + 1) + y]
v2 = bm.verts[x * (grid_size + 1) + y + 1]
v3 = bm.verts[(x + 1) * (grid_size + 1) + y + 1]
v4 = bm.verts[(x + 1) * (grid_size + 1) + y]
bm.faces.new((v1, v2, v3, v4))
bm.to_mesh(mesh)
bm.free()
# Cria shapekeys
obj.shape_key_add(name="Base", from_mix=False) # ShapeKey 0 - base, sem alteração
wave_key = obj.shape_key_add(name="Wave", from_mix=False) # ShapeKey 1 - com a onda
# Calcula a deformação para o shapekey "Wave"
for i, vert in enumerate(obj.data.vertices):
x = vert.co.x
y = vert.co.y
z = (0.4 * math.sin(x * 2) +
0.3 * math.cos(y * 3) +
0.2 * math.sin((x + y) * 4))
wave_key.data[i].co.z = z
# Anima a influência do shapekey da onda
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
# cicla suavemente entre 0 e 1
influence = (math.sin(time) * 0.5) + 0.5
wave_key.value = influence
wave_key.keyframe_insert(data_path="value", frame=frame)
# Posiciona câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
bpy.context.collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (grid_size * grid_spacing / 2, -grid_size * 3 * grid_spacing, grid_size * 1.5 * grid_spacing)
cam.rotation_euler = (math.radians(65), 0, 0)
# Luz
light_data = bpy.data.lights.new("Light", type='SUN')
light = bpy.data.objects.new("Light", light_data)
bpy.context.collection.objects.link(light)
light.location = (0, -10, 10)
light.rotation_euler = (math.radians(45), 0, 0)
# Ajusta frames
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de tela de ondas via shapekey criada com sucesso!")
Como usar:
Roda o script no editor "Scripting" do Blender.
A malha inicial é um plano subdividido.
A shapekey “Wave” modificará o plano com a função de onda.
A influência do shapekey “Wave” é animada usando um seno para fazer a malha oscilar.
A câmera e a luz são configuradas.
Se quiser posso ajudar com outros tipos de animações, efeitos, partículas, procedurais mais complexos, etc!
import bpy
import mathutils
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
max_level = 3 # níveis de profundidade do fractal
base_scale = 1.0 # escala do cubo inicial
scale_factor = 0.5 # fator de escala para cada nível
animation_length = 150
frame_start = 1
frame_end = frame_start + animation_length
# Coleção para organizar tudo
collection = bpy.data.collections.new("FractalCubes")
bpy.context.scene.collection.children.link(collection)
def create_cube(location, scale, name):
bpy.ops.mesh.primitive_cube_add(size=1, location=location)
cube = bpy.context.active_object
cube.name = name
cube.scale = (scale, scale, scale)
if collection not in cube.users_collection:
collection.objects.link(cube)
if bpy.context.scene.collection in cube.users_collection:
bpy.context.scene.collection.objects.unlink(cube)
return cube
# Gera fractal recursivamente
def generate_fractal(location, scale, level, name_prefix):
cube = create_cube(location, scale, f"{name_prefix}_L{level}")
if level >= max_level:
return [cube]
cubes = [cube]
offset = scale * 1.5
# Posições para os cubos filhos (6 direções)
directions = [
(offset, 0, 0),
(-offset, 0, 0),
(0, offset, 0),
(0, -offset, 0),
(0, 0, offset),
(0, 0, -offset),
]
for i, dir_vec in enumerate(directions):
new_loc = (
location[0] + dir_vec[0],
location[1] + dir_vec[1],
location[2] + dir_vec[2]
)
cubes += generate_fractal(new_loc, scale * scale_factor, level + 1, f"{name_prefix}_{i}")
return cubes
# Cria todos os cubos do fractal
all_cubes = generate_fractal((0, 0, 0), base_scale, 1, "Cube")
# Anima as escalas para dar efeito de crescimento orgânico
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / animation_length
for i, cube in enumerate(all_cubes):
# Cada cubo cresce e encolhe com atraso e variação
delay = (i / len(all_cubes)) * 2.0
scale_anim = 0.5 + 0.5 * math.sin(2 * math.pi * (t - delay))
scale_anim_clamped = max(scale_anim, 0) # evita escala negativa
cube.scale = (
cube.scale.x * scale_anim_clamped,
cube.scale.y * scale_anim_clamped,
cube.scale.z * scale_anim_clamped,
)
cube.keyframe_insert(data_path="scale", index=-1)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (6, -8, 6)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
light.location = (5, -5, 10)
light.rotation_euler = (math.radians(60), 0, 0)
# Ajusta tempo da animação
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Fractal procedural de cubos criado e animado com sucesso!")
Como funciona
O script gera cubos baseados numa estrutura fractal simples: cada cubo gera 6 cubos filhos nas direções dos eixos XYZ.
Os cubos são escalonados menor a cada nível.
Cada cubo tem uma animação de escala para “crescer e encolher” sincronizada mas com ligeiro atraso para efeito orgânico.
Câmera e luz são configuradas para visualização.
Se quiser posso ajudar a modificar para árvores fractais, estruturas complexas, ou outros tipos de animação procedural, só pedir!
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_rings = 40
ring_radius = 2
ring_thickness = 0.2
ring_spacing = 0.5
animation_length = 300
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para os anéis
collection = bpy.data.collections.new("RingsTunnel")
bpy.context.scene.collection.children.link(collection)
# Função para criar um anel (torus)
def create_ring(location, name):
bpy.ops.mesh.primitive_torus_add(
major_radius=ring_radius,
minor_radius=ring_thickness,
location=location
)
ring = bpy.context.active_object
ring.name = name
if collection not in ring.users_collection:
collection.objects.link(ring)
if bpy.context.scene.collection in ring.users_collection:
bpy.context.scene.collection.objects.unlink(ring)
return ring
# Cria os anéis distribuídos ao longo do eixo Z
rings = []
for i in range(num_rings):
z = i * ring_spacing
ring = create_ring((0, 0, z), f"Ring_{i}")
rings.append(ring)
# Anima os anéis: rotação contínua e movimento ondulatório ao longo de Z
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
for i, ring in enumerate(rings):
# Rotação constante em torno do eixo Z
ring.rotation_euler[2] = time + i * 0.1
# Movimento ondulatório na posição X e Y para efeito de túnel
offset_x = 0.5 * math.sin(time * 3 + i)
offset_y = 0.5 * math.cos(time * 3 + i)
ring.location.x = offset_x
ring.location.y = offset_y
# Move os anéis ao longo de Z para criar efeito de túnel em movimento
z = (i * ring_spacing) - (time * 2) % (num_rings * ring_spacing)
ring.location.z = z
ring.keyframe_insert(data_path="rotation_euler", index=-1)
ring.keyframe_insert(data_path="location", index=0) # X
ring.keyframe_insert(data_path="location", index=1) # Y
ring.keyframe_insert(data_path="location", index=2) # Z
# Configura câmera atrás dos anéis olhando para frente
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (0, -6, ring_spacing * num_rings / 2)
cam.rotation_euler = (math.radians(90), 0, 0)
# Cria luz
light_data = bpy.data.lights.new("Sun", type='SUN')
light = bpy.data.objects.new("Sun", object_data=light_data)
collection.objects.link(light)
light.location = (0, -10, ring_spacing * num_rings)
light.rotation_euler = (math.radians(60), 0, 0)
# Ajusta frames da animação
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural de túnel de anéis criada com sucesso!")
Como usar
Cole o script no editor “Scripting” do Blender.
Execute o script.
Dê play na timeline para ver os anéis rotacionando e se movendo, criando um efeito de túnel hipnótico.
Se quiser outro estilo ou efeito, me avise!
O que faz esse script?
Cria 30 esferas dispostas inicialmente em círculo.
As esferas se movem ao redor do centro em trajetórias circulares, mas o raio delas oscila criando um efeito de "pétalas" abrindo e fechando.
A altura (Z) também oscila para dar um movimento mais fluido.
A câmera e luz são posicionadas para enquadrar a cena.
Se quiser mais scripts de estilos diferentes, só avisar!
Como funciona?
Cria uma grid 20x20 de cubos espaçados regularmente.
Cada cubo tem a altura animada com uma combinação de funções seno e cosseno em x, y e tempo.
Isso gera efeito visual de ondas que se propagam pela grade.
Configura câmera e luz para melhor visualização.
Se quiser scripts com outras técnicas, estilos ou mais efeitos, é só pedir!
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_strands = 15
points_per_strand = 50
strand_length = 10
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para organizar os fios
collection = bpy.data.collections.new("LightStrands")
bpy.context.scene.collection.children.link(collection)
def create_strand(name):
# Cria uma curva Bezier para o fio
curve_data = bpy.data.curves.new(name, type='CURVE')
curve_data.dimensions = '3D'
spline = curve_data.splines.new('POLY')
spline.points.add(points_per_strand - 1) # já tem 1 ponto
# Inicializa pontos na linha reta em Z
for i, point in enumerate(spline.points):
z = (strand_length / points_per_strand) * i
point.co = (0, 0, z, 1)
curve_obj = bpy.data.objects.new(name, curve_data)
collection.objects.link(curve_obj)
# Adiciona bevel para dar espessura
curve_data.bevel_depth = 0.05
curve_data.bevel_resolution = 4
# Cria material emissivo
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
emission = mat.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Color'].default_value = (1, 0.5, 0.1, 1) # cor laranja
emission.inputs['Strength'].default_value = 5.0
output = mat.node_tree.nodes.get('Material Output')
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
curve_obj.data.materials.append(mat)
return curve_obj, spline.points
# Cria os fios
strands = []
for i in range(num_strands):
strand_name = f"Strand_{i}"
strand_obj, points = create_strand(strand_name)
strands.append((strand_obj, points))
# Anima os fios com ondas ao longo da curva
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / 20.0
for i, (strand_obj, points) in enumerate(strands):
phase = i * 2.0 # fase diferente para cada fio
for j, point in enumerate(points):
z = point.co.z
offset_x = 0.3 * math.sin(t * 4 + j * 0.5 + phase)
offset_y = 0.3 * math.cos(t * 4 + j * 0.5 + phase)
point.co.x = offset_x
point.co.y = offset_y
strand_obj.data.update()
strand_obj.data.keyframe_insert(data_path="splines[0].points[0].co", frame=frame)
# Infelizmente Blender não suporta keyframe individual por ponto,
# então só atualiza curva no frame, animação fica por script ao vivo.
# Posiciona câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (8, -12, 8)
cam.rotation_euler = (math.radians(70), 0, math.radians(45))
# Luz ambiente (fraca, para destacar os emissores)
light_data = bpy.data.lights.new(name="AmbientLight", type='AREA')
light = bpy.data.objects.new(name="AmbientLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, 15)
light.data.energy = 300
# Ajusta frames
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de fios luminosos ondulantes criada com sucesso!")
Observações importantes
O Blender não permite keyframe por coordenada individual dos pontos da spline. Por isso, o movimento obtido é por atualização frame a frame via script (aqui simulada invertendo keyframe na spline, mas a animação real precisa rodar dentro do tempo).
Para renderizado e visualização fluida, use o play da timeline.
Se quiser outra ideia, estilo ou função procedural, só avisar!
Então o script pode rodar usando animação por script em tempo real, mas não com keyframes inseridos diretamente em pontos da curva.
Resumo da correção
Remova ou comente a linha que insere keyframe em pontos da curva.
Use somente strand_obj.data.update() para atualizar a curva.
Para animação interativa, seria necessário usar handlers (bpy.app.handlers.frame_change_pre) para atualizar a curva a cada troca de frame.
Código atualizado corrigido (trecho relevante)
python
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / 20.0
for i, (strand_obj, points) in enumerate(strands):
phase = i * 2.0 # fase diferente para cada fio
for j, point in enumerate(points):
z = point.co.z
offset_x = 0.3 * math.sin(t * 4 + j * 0.5 + phase)
offset_y = 0.3 * math.cos(t * 4 + j * 0.5 + phase)
point.co.x = offset_x
point.co.y = offset_y
# Atualiza a curva após alterar pontos
strand_obj.data.update()
# OBS: não funciona keyframizar pontos individuais da spline, então comente ou remova a linha abaixo
# strand_obj.data.keyframe_insert(data_path="splines[0].points[0].co", frame=frame)
Se deseja, posso ajudar a transformar esse script para usar handlers para animação rodando em tempo real, sem precisar keyframe! Quer?
import bpy
import math
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_strands = 15
points_per_strand = 50
strand_length = 10
# Cria coleção para os fios
collection = bpy.data.collections.new("LightStrands")
bpy.context.scene.collection.children.link(collection)
def create_strand(name):
curve_data = bpy.data.curves.new(name, type='CURVE')
curve_data.dimensions = '3D'
spline = curve_data.splines.new('POLY')
spline.points.add(points_per_strand - 1) # já tem 1 ponto
# Inicializa pontos em linha reta no eixo Z
for i, point in enumerate(spline.points):
z = (strand_length / points_per_strand) * i
point.co = (0, 0, z, 1)
curve_obj = bpy.data.objects.new(name, curve_data)
collection.objects.link(curve_obj)
# Bevel para espessura
curve_data.bevel_depth = 0.05
curve_data.bevel_resolution = 4
# Material emissivo
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
emission_node = nodes.new('ShaderNodeEmission')
emission_node.inputs['Color'].default_value = (1, 0.5, 0.1, 1)
emission_node.inputs['Strength'].default_value = 5.0
output_node = nodes.new('ShaderNodeOutputMaterial')
links.new(emission_node.outputs['Emission'], output_node.inputs['Surface'])
curve_obj.data.materials.append(mat)
return curve_obj, spline.points
# Cria os fios
strands = []
for i in range(num_strands):
strand_name = f"Strand_{i}"
strand_obj, points = create_strand(strand_name)
strands.append((strand_obj, points))
# Função que atualiza as curvas a cada frame
def animate_strands(scene):
frame = scene.frame_current
t = frame / 20.0
for i, (strand_obj, points) in enumerate(strands):
phase = i * 2.0
for j, point in enumerate(points):
offset_x = 0.3 * math.sin(t * 4 + j * 0.5 + phase)
offset_y = 0.3 * math.cos(t * 4 + j * 0.5 + phase)
z = (strand_length / points_per_strand) * j # mantém z fixo
point.co.x = offset_x
point.co.y = offset_y
point.co.z = z
strand_obj.data.update()
# Remove handler antigo (se existir), para evitar múltiplas chamadas duplicadas
for handler in bpy.app.handlers.frame_change_pre:
if handler.__name__ == 'animate_strands':
bpy.app.handlers.frame_change_pre.remove(handler)
# Adiciona o handler de frame change
bpy.app.handlers.frame_change_pre.append(animate_strands)
# Posiciona câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (8, -12, 8)
cam.rotation_euler = (math.radians(70), 0, math.radians(45))
# Luz ambiente
light_data = bpy.data.lights.new(name="AmbientLight", type='AREA')
light = bpy.data.objects.new(name="AmbientLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, 15)
light.data.energy = 300
# Ajusta frames
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 250
print("Handler de animação procedural ativado. Use Play para ver as curvas animadas.")
Como funciona
O handler animate_strands é chamado a cada frame.
Ele recalcula e atualiza as posições dos pontos de todas as curvas para criar as ondulações.
Não usa keyframes nos pontos, pois Blender não suporta.
A animação é exatamente dependente da timeline, basta dar play para ver.
O handler é automaticamente limpo antes de adicionar para evitar duplicatas.
Para usar
Copie o script e execute-o na aba Scripting.
Dê Play na timeline.
Você verá as curvas se animando com o efeito de ondulação dinâmica.
Se quiser, posso ajudar a criar handlers mais complexos ou adicionar controles para essa animação! Quer algo?
import bpy
import math
import random
from mathutils import Vector
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_particles = 30
area_size = 8
max_link_distance = 3.0
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("ParticleNetwork")
bpy.context.scene.collection.children.link(collection)
# Cria partículas (esferas)
particles = []
for i in range(num_particles):
loc = (
random.uniform(-area_size, area_size),
random.uniform(-area_size, area_size),
random.uniform(-area_size, area_size)
)
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.15, location=loc)
obj = bpy.context.active_object
obj.name = f"Particle_{i}"
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
particles.append(obj)
# Função para criar ou atualizar uma curva entre dois pontos
def create_or_update_edge(name, start_obj, end_obj):
# Verifica se já existe objeto com esse nome
curve_obj = bpy.data.objects.get(name)
if curve_obj is None:
# Cria curva nova
curve_data = bpy.data.curves.new(name, type='CURVE')
curve_data.dimensions = '3D'
spline = curve_data.splines.new('POLY')
spline.points.add(1) # total 2 pontos
curve_obj = bpy.data.objects.new(name, curve_data)
collection.objects.link(curve_obj)
# Material emissivo para destaque
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
emission = mat.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Color'].default_value = (0.1, 0.5, 1.0, 1)
emission.inputs['Strength'].default_value = 5.0
output = mat.node_tree.nodes.get('Material Output')
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
curve_obj.data.materials.append(mat)
else:
spline = curve_obj.data.splines[0]
# Atualiza pontos para os locais atuais dos objetos
spline.points[0].co = (*start_obj.location, 1)
spline.points[1].co = (*end_obj.location, 1)
curve_obj.data.update()
return curve_obj
# Gera pares de partículas que serão conectados se estiverem próximas
edges_dict = {}
def update_edges():
# Remove edges antigas que não deveriam existir mais
to_remove = []
for key in edges_dict.keys():
i, j = key
p1 = particles[i]
p2 = particles[j]
dist = (p1.location - p2.location).length
if dist > max_link_distance:
# Remove curva do Blender e da dict
obj = edges_dict[key]
bpy.data.objects.remove(obj, do_unlink=True)
to_remove.append(key)
for key in to_remove:
edges_dict.pop(key)
# Cria ou atualiza edges
for i in range(num_particles):
for j in range(i+1, num_particles):
p1 = particles[i]
p2 = particles[j]
dist = (p1.location - p2.location).length
if dist <= max_link_distance:
key = (i, j)
if key not in edges_dict:
edge_obj = create_or_update_edge(f"Edge_{i}_{j}", p1, p2)
edges_dict[key] = edge_obj
else:
# Atualiza posição dos pontos da curva
edge_obj = edges_dict[key]
spline = edge_obj.data.splines[0]
spline.points[0].co = (*p1.location, 1)
spline.points[1].co = (*p2.location, 1)
edge_obj.data.update()
# Anima partículas com movimentos orgânicos
def animate_particles(scene):
frame = scene.frame_current
t = frame / 30.0
for i, p in enumerate(particles):
offset = Vector((
0.3 * math.sin(t + i),
0.3 * math.cos(t * 1.3 + i * 1.7),
0.3 * math.sin(t * 1.5 + i * 2.1),
))
base_pos = p.location
p.location = base_pos + offset
update_edges()
# Remove handler ativo se existir e adiciona o atual
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == 'animate_particles':
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_particles)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (area_size*2, -area_size*2, area_size*2)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
light.location = (area_size*2, -area_size*2, area_size*3)
light.rotation_euler = (math.radians(60), 0, 0)
# Configura frames
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Rede procedural de partículas animadas criada com sucesso! Dê play para ver funcionar.")
O que esse script faz?
Cria partículas (esferas) em posições aleatórias 3D.
Cria curvas (arestas) conectando partículas que estão próximas até uma distância limite.
Anima as partículas com pequenos deslocamentos senoidais para parecerem se movimentar organicamente.
Atualiza as conexões (arestas) em tempo real.
Usa handler para atualizar a animação frame a frame.
Se quiser que eu modifique para ter cores, aumentar número de partículas, ou outras funcionalidades, só avisar!
import bpy
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_cubes = 100
spiral_turns = 4
max_radius = 8
max_height = 12
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para os cubos
collection = bpy.data.collections.new("SpiralCubes")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_cube(location, name):
bpy.ops.mesh.primitive_cube_add(size=0.3, location=location)
cube = bpy.context.active_object
cube.name = name
if collection not in cube.users_collection:
collection.objects.link(cube)
if bpy.context.scene.collection in cube.users_collection:
bpy.context.scene.collection.objects.unlink(cube)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
cube.data.materials.append(mat)
return cube, mat
# Cria os cubos na espiral
cubes = []
materials = []
for i in range(num_cubes):
angle = 2 * math.pi * spiral_turns * i / num_cubes
radius = max_radius * i / num_cubes
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = max_height * i / num_cubes
cube, mat = create_cube((x, y, z), f"Cube_{i}")
cubes.append(cube)
materials.append(mat)
# Anima a escala e cor dos cubos
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / 30.0
for i, (cube, mat) in enumerate(zip(cubes, materials)):
# Escala pulsante com fase e posição variáveis
scale = 0.5 + 0.5 * math.sin(t * 4 + i * 0.3)
cube.scale = (scale, scale, scale)
cube.keyframe_insert(data_path="scale", index=-1)
# Cor baseada em HSV variando no tempo e índice
h = (t * 0.2 + i / num_cubes) % 1.0
s, v = 1.0, 1.0
r, g, b = hsv_to_rgb(h, s, v)
# Atualiza material emissivo para melhor destaque
nodes = mat.node_tree.nodes
if "Emission" not in nodes:
emission = nodes.new('ShaderNodeEmission')
output = nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
else:
emission = nodes["Emission"]
emission.inputs['Color'].default_value = (r, g, b, 1)
emission.inputs['Strength'].default_value = 3.0
emission.inputs['Color'].keyframe_insert("default_value", frame=frame)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (max_radius * 1.5, -max_radius * 2, max_height * 1.2)
cam.rotation_euler = (math.radians(65), 0, math.radians(45))
# Luz ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (max_radius, -max_radius, max_height * 2)
light.data.energy = 1000
light.data.size = 5
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural de espiral de cubos criada com sucesso!")
Como usar
Abra o Blender, vá para a aba Scripting.
Cole o script e clique em Run Script.
Dê play na Timeline para ver a animação dos cubos crescendo/encolhendo e mudando de cor em uma espiral 3D.
Se quiser, posso ajudar a ajustar, adicionar efeitos ou criar outro tipo de estrutura também!
import bpy
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_rings = 40
max_radius = 8
ring_thickness = 0.1
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("ConcentricRings")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_ring(name, radius):
bpy.ops.mesh.primitive_torus_add(
major_radius=radius,
minor_radius=ring_thickness,
rotation=(math.radians(90), 0, 0)
)
ring = bpy.context.active_object
ring.name = name
if collection not in ring.users_collection:
collection.objects.link(ring)
if bpy.context.scene.collection in ring.users_collection:
bpy.context.scene.collection.objects.unlink(ring)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
ring.data.materials.append(mat)
return ring, mat
rings = []
materials = []
for i in range(num_rings):
radius = max_radius * (i + 1) / num_rings
ring, mat = create_ring(f"Ring_{i}", radius)
rings.append(ring)
materials.append(mat)
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / 30.0
for i, (ring, mat) in enumerate(zip(rings, materials)):
# Escala pulsatil para efeito de onda
scale_factor = 0.8 + 0.4 * math.sin(t * 3 - i * 0.4)
ring.scale = (scale_factor, scale_factor, scale_factor)
ring.keyframe_insert(data_path="scale", index=-1)
# Cor variando ciclicamente
h = (t * 0.2 + i / num_rings) % 1.0
s, v = 1.0, 1.0
r, g, b = hsv_to_rgb(h, s, v)
nodes = mat.node_tree.nodes
if "Emission" not in nodes:
emission = nodes.new('ShaderNodeEmission')
output = nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
else:
emission = nodes["Emission"]
emission.inputs['Color'].default_value = (r, g, b, 1)
emission.inputs['Strength'].default_value = 4.0
emission.inputs['Color'].keyframe_insert('default_value', frame=frame)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (0, -max_radius * 3, max_radius * 1.5)
cam.rotation_euler = (math.radians(70), 0, 0)
# Luz ambiente suave
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, -max_radius * 2, max_radius * 3)
light.data.energy = 1200
light.data.size = 10
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação procedural de anéis concêntricos criada com sucesso!")
Como usar
Abra o Blender e vá para a aba Scripting.
Cole o script.
Clique em Run Script.
Dê play para ver os anéis pulsarem e mudarem de cor.
Se quiser outro estilo ou técnica, me avise!
import bpy
import random
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_particles = 100
space_radius = 10
animation_length = 300
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("FlyingParticles")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_particle(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.1, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
emission = mat.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Strength'].default_value = 5.0
output = mat.node_tree.nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
obj.data.materials.append(mat)
return obj, mat, emission
# Cria partículas em posições aleatórias
particles = []
for i in range(num_particles):
pos = (
random.uniform(-space_radius, space_radius),
random.uniform(-space_radius, space_radius),
random.uniform(-space_radius, space_radius)
)
p, mat, emission = create_particle(pos, f"Particle_{i}")
particles.append((p, mat, emission))
# Handler para animação procedural
def animate_particles(scene):
frame = scene.frame_current
t = frame / 25.0
for i, (p, mat, emission) in enumerate(particles):
base_loc = p.location
# Movimento oscilatório orgânico
offset = (
0.5 * math.sin(t * 2 + i),
0.5 * math.cos(t * 1.5 + i * 1.2),
0.5 * math.sin(t * 1.8 + i * 2.5)
)
new_loc = (
base_loc.x + offset[0],
base_loc.y + offset[1],
base_loc.z + offset[2]
)
p.location = new_loc
# Cor variando em HSV para RGB ciclos vibrantes
h = (t * 0.3 + i / num_particles) % 1.0
s, v = 1.0, 1.0
r, g, b = hsv_to_rgb(h, s, v)
emission.inputs['Color'].default_value = (r, g, b, 1)
# Remove handler anterior para evitar duplicidade
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == "animate_particles":
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_particles)
# Posiciona câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (space_radius * 1.5, -space_radius * 2, space_radius * 1.5)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz ambiente suave
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, space_radius * 3)
light.data.energy = 600
light.data.size = 15
# Configura timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de partículas voadoras criada com sucesso! Use Play para ver o efeito.")
Como usar
Execute o script no Blender (aba Scripting).
Dê Play na timeline.
As esferas vão se mover organicamente e mudar de cor ciclicamente, simulando um campo de partículas vivas.
Se desejar outro tipo de efeito ou estrutura, só avisar!
import bpy
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_spheres = 60
helix_radius = 4
helix_pitch = 0.3 # distância vertical entre voltas da hélice
num_turns = 5
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para as esferas
collection = bpy.data.collections.new("HelixRibbon")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.2, location=location)
sphere = bpy.context.active_object
sphere.name = name
if collection not in sphere.users_collection:
collection.objects.link(sphere)
if bpy.context.scene.collection in sphere.users_collection:
bpy.context.scene.collection.objects.unlink(sphere)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
sphere.data.materials.append(mat)
return sphere, mat
# Cria esferas posicionadas na hélice
spheres = []
materials = []
for i in range(num_spheres):
t = 2 * math.pi * num_turns * i / num_spheres
x = helix_radius * math.cos(t)
y = helix_radius * math.sin(t)
z = helix_pitch * t
sphere, mat = create_sphere((x, y, z), f"Sphere_{i}")
spheres.append(sphere)
materials.append(mat)
# Animația da escala e cor ao redor da hélice
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 25.0
for i, (sphere, mat) in enumerate(zip(spheres, materials)):
# Faz a esfera pulsar em escala
scale = 0.5 + 0.5 * math.sin(time * 5 + i)
sphere.scale = (scale, scale, scale)
sphere.keyframe_insert(data_path="scale", index=-1)
# Cor variando ao longo do tempo
h = (time * 0.2 + i / num_spheres) % 1.0
s, v = 1.0, 1.0
r, g, b = hsv_to_rgb(h, s, v)
nodes = mat.node_tree.nodes
emission = nodes.get("Emission")
if emission is None:
emission = nodes.new('ShaderNodeEmission')
output = nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
emission.inputs['Color'].default_value = (r, g, b, 1)
emission.inputs['Strength'].default_value = 4.0
emission.inputs['Color'].keyframe_insert("default_value", frame=frame)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (helix_radius * 3, -helix_radius * 5, helix_pitch * num_turns * 0.6)
cam.rotation_euler = (math.radians(70), 0, math.radians(45))
# Luz ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (helix_radius * 2, -helix_radius * 2, helix_pitch * num_turns)
light.data.energy = 1500
light.data.size = 10
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de fita helicoidal criada com sucesso!")
Como usar
Cole o script no Blender (aba Scripting).
Execute o script.
Pressione Play na timeline para ver a animação da fita helicoidal com esferas pulsando e coloridas.
Se quiser outro tipo de estrutura ou efeito, só avisar!
import bpy
import math
import random
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_particles = 500
spiral_arms = 3
max_radius = 12
max_height = 2
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção para partículas
collection = bpy.data.collections.new("GalaxyParticles")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_particle(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.05, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
emission = mat.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Strength'].default_value = 5.0
output = mat.node_tree.nodes.get('Material Output')
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
obj.data.materials.append(mat)
return obj, mat, emission
particles = []
for i in range(num_particles):
# Distribui partículas em braços de espiral com ruído radial e angular
arm_index = i % spiral_arms
distance = random.uniform(0.1, 1.0) ** 1.5 * max_radius
angle = distance * 4 + (2 * math.pi * arm_index) / spiral_arms + random.uniform(-0.2, 0.2)
x = distance * math.cos(angle)
y = distance * math.sin(angle)
z = random.uniform(-max_height, max_height)
p, mat, emission = create_particle((x, y, z), f"Particle_{i}")
particles.append((p, mat, emission))
def animate_galaxy(scene):
frame = scene.frame_current
t = frame / 40.0
for i, (p, mat, emission) in enumerate(particles):
# Rotação ao redor do centro
arm_index = i % spiral_arms
base_dist = (p.location.x ** 2 + p.location.y ** 2) ** 0.5
rotation_speed = 0.5 / (0.1 + base_dist)
angle = math.atan2(p.location.y, p.location.x) + t * rotation_speed
radius = base_dist
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = p.location.z
p.location = (x, y, z)
# Variação de cor pulsante baseada no tempo e índice
h = (t * 0.1 + i / num_particles) % 1.0
s, v = 1.0, 1.0
r, g, b = hsv_to_rgb(h, s, v)
emission.inputs['Color'].default_value = (r, g, b, 1)
# Remove handler caso já exista para evitar duplicação
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == 'animate_galaxy':
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_galaxy)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (0, -max_radius * 3, max_radius * 1.8)
cam.rotation_euler = (math.radians(75), 0, 0)
# Luz ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, max_radius * 4)
light.data.energy = 1000
light.data.size = 20
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de galáxia espiral criada com sucesso! Dê play para ver a magia.")
Como usar:
Cole o script no Blender (aba Scripting) e execute.
Dê Play na timeline para ver as partículas orbitando em braços espirais com cores pulsantes.
Se quiser outros estilos, texturas ou tipos de animação, peça sem problemas!
Como usar:
Cole e rode no Blender.
Dê play na timeline para ver cubos crescendo em sequência, formando a estrutura fractal.
Posso ajudar a fazer versões mais complexas ou outros tipos de fractais também!
import bpy
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_rings = 5
spheres_per_ring = 20
ring_spacing = 2.5
max_orbit_speed = 0.05
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("OrbitingSpheres")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.2, location=location)
sphere = bpy.context.active_object
sphere.name = name
if collection not in sphere.users_collection:
collection.objects.link(sphere)
if bpy.context.scene.collection in sphere.users_collection:
bpy.context.scene.collection.objects.unlink(sphere)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
sphere.data.materials.append(mat)
return sphere, mat
# Cria esferas em anéis
spheres = []
materials = []
for ring in range(num_rings):
radius = ring_spacing * (ring + 1)
for i in range(spheres_per_ring):
angle = 2 * math.pi * i / spheres_per_ring
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0
sphere, mat = create_sphere((x, y, z), f"Sphere_R{ring}_S{i}")
spheres.append((sphere, ring, i))
materials.append(mat)
# Animação das órbitas e das cores
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
time = (frame - frame_start) / 20.0
for idx, (sphere, ring, i) in enumerate(spheres):
radius = ring_spacing * (ring + 1)
orbit_speed = max_orbit_speed / (ring + 1)
angle = 2 * math.pi * i / spheres_per_ring + time * orbit_speed * 2 * math.pi
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = 0
sphere.location = (x, y, z)
sphere.keyframe_insert(data_path="location")
# Atualiza cor HSV baseada na posição e o tempo
h = (time * 0.3 + ring / num_rings + i / spheres_per_ring) % 1.0
s = 1.0
v = 1.0
r, g, b = hsv_to_rgb(h, s, v)
mat = materials[idx]
nodes = mat.node_tree.nodes
emission = nodes.get("Emission")
if emission is None:
emission = nodes.new('ShaderNodeEmission')
output = nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
emission.inputs['Color'].default_value = (r, g, b, 1)
emission.inputs['Strength'].default_value = 4.0
emission.inputs['Color'].keyframe_insert(data_path="default_value", frame=frame)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (0, -num_rings * ring_spacing * 5, num_rings * ring_spacing * 2)
cam.rotation_euler = (math.radians(75), 0, 0)
# Luz suave ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, num_rings * ring_spacing * 4)
light.data.energy = 1200
light.data.size = 15
# Ajusta a timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de esferas orbitais criada com sucesso!")
Como usar:
Execute o script no Blender (aba Scripting).
Dê play na timeline para ver as esferas orbitando em anéis com cores pulsantes.
Se quiser outro estilo ou ajuste, só avisar!
import bpy
import math
import mathutils
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
max_level = 4
base_length = 3.0
length_factor = 0.7
base_radius = 0.1
radius_factor = 0.6
branch_angle = math.radians(30)
animation_length = 200
frame_start = 1
frame_end = frame_start + animation_length
collection = bpy.data.collections.new("FractalTree")
bpy.context.scene.collection.children.link(collection)
def create_branch(start, direction, length, radius, name):
bpy.ops.mesh.primitive_cylinder_add(
radius=radius,
depth=length,
location=start + direction * (length / 2),
rotation=direction.to_track_quat('Z', 'Y').to_euler()
)
branch = bpy.context.active_object
branch.name = name
if collection not in branch.users_collection:
collection.objects.link(branch)
if bpy.context.scene.collection in branch.users_collection:
bpy.context.scene.collection.objects.unlink(branch)
return branch
def generate_tree(start, direction, length, radius, level, name_prefix):
branches = []
branch = create_branch(start, direction, length, radius, f"{name_prefix}_L{level}")
branches.append(branch)
if level >= max_level:
return branches
# Posição final da branch para novos ramos
end_pos = start + direction * length
# Direções para os dois novos galhos (esquerda e direita)
rot_quat_left = mathutils.Quaternion(direction, branch_angle)
rot_quat_right = mathutils.Quaternion(direction, -branch_angle)
dir_left = rot_quat_left @ direction
dir_right = rot_quat_right @ direction
branches += generate_tree(end_pos, dir_left, length * length_factor, radius * radius_factor, level + 1, name_prefix + "L")
branches += generate_tree(end_pos, dir_right, length * length_factor, radius * radius_factor, level + 1, name_prefix + "R")
return branches
# Gera árvore fractal
tree_branches = generate_tree(
start=mathutils.Vector((0, 0, 0)),
direction=mathutils.Vector((0, 0, 1)),
length=base_length,
radius=base_radius,
level=1,
name_prefix="Branch"
)
# Controla crescimento animado via escala das branches em Z
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / animation_length
for branch in tree_branches:
# Calcula atraso baseado no nível e nome
level = int(branch.name.split('_L')[-1])
growth = max(0.0, min(1.0, (t * max_level) - (level - 1)))
# Escalando em Z para simular crescimento
branch.scale.z = growth
branch.keyframe_insert(data_path="scale", index=2)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (8, -8, 10)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light = bpy.data.objects.new(name="Sun", object_data=light_data)
collection.objects.link(light)
light.location = (10, -10, 15)
light.rotation_euler = (math.radians(60), 0, 0)
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Árvore fractal animada criada com sucesso!")
Como usar
Cole o script no Blender (aba Scripting).
Execute.
Dê play na timeline para ver os galhos da árvore crescendo progressivamente.
Posso ajudar a aprimorar este script com folhas, variações, ou outro efeito! Quer?
Instruções
Rode o script no Blender.
Dê play para ver as curvas ondulando como se fossem ondas fluindo.
Pode modificar parâmetros para alterar o efeito!
Quer mais scripts com efeitos específicos? É só pedir!
import bpy
import random
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_particles = 150
space_radius = 8
animation_length = 300
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("FloatingParticles")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_particle(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.12, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
emission = mat.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Strength'].default_value = 5.0
output = mat.node_tree.nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
obj.data.materials.append(mat)
return obj, mat, emission
particles = []
for i in range(num_particles):
pos = (
random.uniform(-space_radius, space_radius),
random.uniform(-space_radius, space_radius),
random.uniform(-space_radius, space_radius)
)
p, mat, emission = create_particle(pos, f"Particle_{i}")
particles.append((p, mat, emission))
def animate_particles(scene):
frame = scene.frame_current
t = frame / 40.0
for i, (p, mat, emission) in enumerate(particles):
# Movimento suave e orgânico
offset = (
0.5 * math.sin(t * 1.2 + i),
0.5 * math.cos(t * 1.5 + i * 1.3),
0.5 * math.sin(t * 1.1 + i * 1.7)
)
base_loc = p.location
p.location = (
base_loc.x + offset[0],
base_loc.y + offset[1],
base_loc.z + offset[2]
)
# Variação de escala
scale_factor = 0.5 + 0.5 * math.sin(t * 2 + i)
p.scale = (scale_factor, scale_factor, scale_factor)
# Cor variando em HSV para RGB
h = (t * 0.3 + i / num_particles) % 1.0
r, g, b = hsv_to_rgb(h, 1, 1)
emission.inputs['Color'].default_value = (r, g, b, 1)
# Remove handlers duplicados
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == 'animate_particles':
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_particles)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (space_radius * 2, -space_radius * 2, space_radius * 2)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, space_radius * 4)
light.data.energy = 600
light.data.size = 15
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Campo de partículas flutuantes criado com sucesso! Use Play para ver a animação.")
Como usar
Execute o script no Blender.
Dê play para ver as partículas se movimentando, mudando de cor e tamanho organicamente.
Quer alguma variação ou efeito específico? É só pedir!
Como usar
Cole e rode o script no Blender.
Use a timeline para tocar a animação e veja os cubos se moverem em ondas fluidas.
Quer outra animação ou efeito? Pode pedir!
import bpy
import random
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_spheres = 50
space_limit = 8
animation_length = 300
frame_start = 1
frame_end = frame_start + animation_length
# Cria coleção
collection = bpy.data.collections.new("ChaoticSpheres")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
emission = mat.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Strength'].default_value = 6.0
output = mat.node_tree.nodes.get('Material Output')
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
obj.data.materials.append(mat)
return obj, mat, emission
spheres = []
for i in range(num_spheres):
pos = (
random.uniform(-space_limit, space_limit),
random.uniform(-space_limit, space_limit),
random.uniform(-space_limit, space_limit)
)
s, mat, emission = create_sphere(pos, f"Sphere_{i}")
spheres.append((s, mat, emission))
def animate_spheres(scene):
frame = scene.frame_current
t = frame / 20.0
for i, (s, mat, emission) in enumerate(spheres):
# Trajetória caótica usando senos, cossenos, combinações
x = (3 * math.sin(t + i) +
2 * math.cos(t * 0.5 + i * 1.5) +
1 * math.sin(t * 2 + i * 0.3))
y = (3 * math.cos(t + i * 1.2) +
2 * math.sin(t * 0.7 + i) +
1 * math.cos(t * 1.5 + i * 0.5))
z = (2 * math.sin(t * 1.1 + i) +
1 * math.cos(t * 0.9 + i * 1.3))
s.location = (x, y, z)
# Pulsação de escala
scale = 0.4 + 0.3 * math.sin(t * 3 + i)
s.scale = (scale, scale, scale)
# Cor variando em HSV para RGB
h = (t * 0.2 + i / num_spheres) % 1.0
r, g, b = hsv_to_rgb(h, 1, 1)
emission.inputs['Color'].default_value = (r, g, b, 1)
# Remove handlers duplicados
for h in bpy.app.handlers.frame_change_pre:
if h.__name__ == 'animate_spheres':
bpy.app.handlers.frame_change_pre.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_spheres)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (15, -15, 12)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, 0, 20)
light.data.energy = 800
light.data.size = 20
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de esferas caóticas criada! Dê play para visualizar.")
Como usar
Cole o script no Blender.
Execute e dê play. As esferas vão se movimentar de forma caótica, mudando cor e tamanho.
Se quiser outra ideia ou estilo, é só dizer!
import bpy
import math
import colorsys
# Limpa a cena
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Parâmetros
num_spheres = 80
spiral_turns = 5
max_radius = 6
path_height = 10
animation_length = 250
frame_start = 1
frame_end = frame_start + animation_length
# Coleção para organização
collection = bpy.data.collections.new("SpiralFlow")
bpy.context.scene.collection.children.link(collection)
def hsv_to_rgb(h, s, v):
return colorsys.hsv_to_rgb(h, s, v)
def create_sphere(location, name):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.2, location=location)
obj = bpy.context.active_object
obj.name = name
if collection not in obj.users_collection:
collection.objects.link(obj)
if bpy.context.scene.collection in obj.users_collection:
bpy.context.scene.collection.objects.unlink(obj)
mat = bpy.data.materials.new(name + "_Mat")
mat.use_nodes = True
obj.data.materials.append(mat)
return obj, mat
spheres = []
materials = []
for i in range(num_spheres):
angle = 2 * math.pi * spiral_turns * i / num_spheres
radius = max_radius * (i / num_spheres)
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = path_height * (i / num_spheres)
sphere, mat = create_sphere((x, y, z), f"Sphere_{i}")
spheres.append(sphere)
materials.append(mat)
# Animação das esferas
for frame in range(frame_start, frame_end + 1):
bpy.context.scene.frame_set(frame)
t = (frame - frame_start) / 30.0
for i, (sphere, mat) in enumerate(zip(spheres, materials)):
# Movimento oscilatório em torno do eixo central
angle = 2 * math.pi * spiral_turns * i / num_spheres + t * 2
radius_variation = 0.1 * math.sin(t * 5 + i)
radius = max_radius * (i / num_spheres) + radius_variation
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = path_height * (i / num_spheres) + 0.3 * math.sin(t * 3 + i)
sphere.location = (x, y, z)
sphere.keyframe_insert(data_path="location")
# Variação de cor HSV para RGB
h = (t * 0.2 + i / num_spheres) % 1.0
s, v = 1.0, 1.0
r, g, b = hsv_to_rgb(h, s, v)
nodes = mat.node_tree.nodes
emission = nodes.get("Emission")
if emission is None:
emission = nodes.new('ShaderNodeEmission')
output = nodes['Material Output']
mat.node_tree.links.new(emission.outputs['Emission'], output.inputs['Surface'])
emission.inputs['Color'].default_value = (r, g, b, 1)
emission.inputs['Strength'].default_value = 5.0
emission.inputs['Color'].keyframe_insert("default_value", frame=frame)
# Configura câmera
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
collection.objects.link(cam)
bpy.context.scene.camera = cam
cam.location = (max_radius * 3, -max_radius * 3, path_height * 1.5)
cam.rotation_euler = (math.radians(60), 0, math.radians(45))
# Luz ambiente
light_data = bpy.data.lights.new(name="AreaLight", type='AREA')
light = bpy.data.objects.new(name="AreaLight", object_data=light_data)
collection.objects.link(light)
light.location = (0, -max_radius * 3, path_height * 3)
light.data.energy = 1200
light.data.size = 15
# Ajusta timeline
bpy.context.scene.frame_start = frame_start
bpy.context.scene.frame_end = frame_end
print("Animação de espiral fluida criada com sucesso! Dê play para ver.")
Como usar:
Cole o script no Blender, execute.
Dê play para ver as esferas se movimentando formando uma espiral com cores dinâmicas.