blender 3d: faça um script de uma animação procedual complexa de uma bola derrubando uma pilha de cubos
Assistant
Claro! Aqui está um exemplo de um script em Python para o Blender que cria uma animação procedural onde uma esfera derruba uma pilha de cubos. O script cria uma pilha de cubos empilhados, adiciona uma esfera, posiciona-a de forma que ela caia sobre a pilha e usa física para simular a colisão e a queda dos cubos.
Para usar:
Abra o Blender.
Vá para a aba Scripting.
Crie um novo texto e cole o código.
Execute o script.
O script utiliza o sistema de física do Blender (rigid bodies) para a simulação.
python
import bpy
import mathutils
# Limpa a cena (objetos mesh)
def clear_scene():
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type == 'MESH' or obj.type == 'EMPTY':
obj.select_set(True)
bpy.ops.object.delete()
clear_scene()
# Configura o motor de física para Rigid Body
bpy.context.scene.rigidbody_world.enabled = True
# Define parâmetros
cube_size = 1
stack_height = 10
stack_width = 3
stack_depth = 3
gap = 0.01 # pequeno espaço entre cubos para evitar interpenetrações
# Cria a pilha de cubos
cubes = []
start_x = -(stack_width / 2) * (cube_size + gap)
start_y = 0
start_z = cube_size / 2 # para ficar em cima do plano
for i in range(stack_height):
for x in range(stack_width):
for y in range(stack_depth):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (
start_x + x * (cube_size + gap),
start_y + y * (cube_size + gap),
start_z + i * (cube_size + gap)
)
cube.name = f"Cube_{i}_{x}_{y}"
# Adiciona rigid body passivo (não movem-se, só interagem)
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cubes.append(cube)
# Cria o solo
bpy.ops.mesh.primitive_plane_add(size=20)
floor = bpy.context.object
floor.location = (0, 0, 0)
floor.name = "Floor"
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1
# Cria a esfera que vai derrubar a pilha
bpy.ops.mesh.primitive_uv_sphere_add(radius=cube_size * 1.5)
sphere = bpy.context.object
sphere.name = "Sphere"
sphere.location = (0, -5, stack_height * (cube_size + gap) + 5)
# Adiciona rigid body ativo e define massa
bpy.ops.rigidbody.object_add()
sphere.rigid_body.mass = 10
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.friction = 0.5
sphere.rigid_body.restitution = 0.2 # pouco quique
# Define keyframe para a esfera no frame 1 (posição inicial)
sphere.keyframe_insert(data_path="location", frame=1)
# Aplique uma força inicial para a esfera "empurrar" a pilha (opcional)
# Em vez de aplicar força, vamos posicionar a esfera para cair naturalmente pela gravidade.
# Poderia definir velocidade inicial via rigid body settings (mas Blender não oferece direto via Python)
# Então vamos mover a esfera para frente com keyframes
# Define animação simples: esfera cai pela gravidade (não precisa de mais force)
# Configura o timeline para 250 frames
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 250
# Ajuste da câmera para melhor visão
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if not cam:
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.location = (10, -20, 15)
cam.rotation_euler = (1.1, 0, 0.8)
bpy.context.scene.camera = cam
# Configura a gravidade (normal é -9.81)
bpy.context.scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Setup completo. Execute a simulação na Timeline para ver a animação.")
Como usar
Cole o script no editor de texto do Blender e execute.
A pilha de cubos será criada no centro.
A esfera será posicionada um pouco acima e para trás, e cairá por gravidade sobre os cubos.
Pressione PLAY na timeline para ver a simulação física rodar e a esfera derrubando os cubos.
Explicação
Criamos cubos empilhados em uma grade 3x3, com altura controlada pela variável stack_height.
O chão (um plano grande) é um Rigidbody passivo que impede que os cubos caiam indefinidamente.
A esfera é maior e mais pesada para derrubar a pilha.
Todas as interações dependem do motor de Física do Blender usando Rigid Bodies.
A animação é procedural, cada execução do script criará a pilha e esfera novamente.
Se quiser aprofundar, pode-se adicionar forças, colisores adicionais, alterar propriedades físicas ou criar curvas de animação para a esfera empurrar a pilha lateralmente.
Se precisar de algo ainda mais complexo ou diferente, me avise!
User
Python: Traceback (most recent call last):
File "\Text", line 15, in
AttributeError: 'NoneType' object has no attribute 'enabled'
Assistant
Esse erro indica que o objeto bpy.context.scene.rigidbody_world está como None, e você está tentando acessar seu atributo .enabled, causando o AttributeError.
No Blender, para acessar o mundo de física de corpos rígidos (rigidbody_world), ele precisa existir previamente. Caso não exista, você deve criá-lo antes de ativar ou alterar propriedades.
Vou ajustar o seu trecho para garantir que o sistema de física de corpos rígidos esteja criado:
python
if bpy.context.scene.rigidbody_world is None:
bpy.context.scene.rigidbody_world = bpy.context.scene.rigidbody_world_add()
bpy.context.scene.rigidbody_world.enabled = True
Porém, o Blender não possui o método rigidbody_world_add() diretamente acessível assim. A forma correta de adicionar um mundo rígido é usando:
python
bpy.ops.rigidbody.world_add()
Então, o jeito correto é:
python
if bpy.context.scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
bpy.context.scene.rigidbody_world.enabled = True
Código corrigido para essa parte:
python
# Ativa o sistema de física Rigid Body world se não existir
if bpy.context.scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
bpy.context.scene.rigidbody_world.enabled = True
Como ajustar o seu script completo (só a parte inicial):
python
import bpy
import mathutils
# Limpa a cena (objetos mesh)
def clear_scene():
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type == 'MESH' or obj.type == 'EMPTY':
obj.select_set(True)
bpy.ops.object.delete()
clear_scene()
# Ativa o sistema de física Rigid Body world se não existir
if bpy.context.scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
bpy.context.scene.rigidbody_world.enabled = True
# depois o resto do script...
Observação
Corrija sempre criando o mundo Rigid Body antes de acessar suas propriedades.
Se quiser rodar um script passo a passo, pode fazer também isso no console do Blender para testar.
Se quiser, posso enviar o script completo já ajustado para evitar este erro. Quer?
User
sim
Assistant
Perfeito! Aqui está o script completo, revisado para garantir que o Rigid Body World seja criado corretamente no Blender antes de ativar a simulação, evitando o AttributeError.
python
User
outro script
Assistant
Claro! Aqui está outro script Python para Blender que cria uma animação procedural de uma bola derrubando uma pilha de cubos, porém com algumas variações para deixar a simulação um pouco diferente e visualmente interessante:
A pilha será uma pirâmide de cubos (não uma grade retangular).
A esfera será lançada lateralmente com uma velocidade inicial (impulso) para "acelerar" o impacto.
Cores aleatórias para os cubos.
O chão tem um pouco de rugosidade para mais realismo.
Script alternativo de animação procedural com bola derrubando pilha piramidal
python
User
outro script
Assistant
Claro! Aqui vai mais um script Python para Blender criando uma animação procedural diferente:
Descrição:
Em vez de uma pilha, criamos uma parede vertical de cubos (uma janela).
Uma bola gigante é lançada para frente, com velocidade inicial real (usando o sistema de física via rigid_body.kinematic + bpy.app.handlers.frame_change_pre para controlar a velocidade).
A parede vai desabar ao ser atingida.
Cubos coloridos que destroem a parede.
Script Blender Python — Bola lançada derrubando uma parede de cubos, com controle de velocidade da esfera
python
User
outro script
Assistant
Claro! Aqui está mais um script Python para Blender com uma animação procedural onde uma bola derruba uma pilha de cubos, porém com um estilo diferente e com efeitos adicionais para tornar a simulação mais interessante:
Script: Bola explosiva derruba pilha de cubos com partículas de explosão
Características:
Pilha de cubos empilhada com física.
Bola “explosiva” que ao colidir gera partículas (fumaça/fogo simples).
Bola tem massa grande e é lançada com velocidade inicial.
Explosão ocorre na colisão (simulada via frame).
python
User
outro script
Assistant
Claro! Aqui está mais um script diferente, com uma abordagem procedural para criar uma cena onde uma bola quica numa pilha de cubos e derruba tudo, com uma câmera animada seguindo a bola durante o movimento.
Script: Bola quicando e derrubando cubos com câmera animada
python
User
outro script
Assistant
Claro! Aqui está mais um script Blender Python procedural, com uma abordagem diferente:
Script: Várias bolas caem de alturas aleatórias sobre uma pilha de cubos e derrubam a pilha
Características:
Pilha de cubos empilhada verticalmente.
Várias pequenas esferas são criadas acima da pilha, em alturas e posições aleatórias.
As esferas caem pela gravidade e colidem com a pilha, derrubando os cubos.
Materiais simples para diferenciar cubos e esferas.
Cena configurada com câmera e iluminação básica.
python
User
outro script
Assistant
Claro! Aqui vai um script novo, diferente dos anteriores, que cria uma animação procedural onde:
Uma rampa é criada.
Cubos são empilhados no topo da rampa.
Uma esfera é lançada rampa abaixo para derrubar os cubos.
A câmera acompanha a ação com uma leve rotação dinâmica.
Script Blender Python: Bola rola rampa e derruba cubos com câmera animada
python
User
outro script
Assistant
Claro! Aqui está mais um script diferente para Blender, criando uma animação procedural onde:
Uma esfera é lançada dentro de um tubo vertical transparente.
Uma pilha de cubos está posicionada no chão.
A bola colide com a pilha derrubando os cubos.
O tubo tem paredes transparentes feitas de planos com material de vidro.
Script: Bola lançada dentro de tubo transparente derruba pilha de cubos
python
User
outro script
Assistant
Claro! Aqui está mais um script bem diferente para o Blender, que cria uma cena procedural com:
Uma pilha de cubos empilhados.
Uma série de pêndulos esféricos pendurados, que ao serem soltos colidem e derrubam os cubos.
Física realista, com pendular oscilando e bola caindo sobre a pilha.
Câmera fixa para observar a cena.
python
User
outro script mais complexo
Assistant
Claro! Vou criar um script mais complexo e detalhado para Blender que implementa uma cena com a seguinte descrição:
Cena complexa procedural: Rube Goldberg simplificado
Descrição:
Uma bola (esfera) é lançada numa rampa.
Ao final da rampa, ela aciona uma gangorra/pivô (balança).
Do outro lado da gangorra, uma caixa é lançada para derrubar uma pilha de cubos (arranjo em forma de pirâmide).
Toda a cena usa física rígida (Rigid Body) para simulação.
Inclui materiais básicos para diferenciar objetos.
Uma câmera animada segue o movimento principal.
Código completo:
python
User
Python: Traceback (most recent call last):
File "\Text.009", line 21, in
AttributeError: 'RigidBodyWorld' object has no attribute 'steps_per_second'
Assistant
O atributo steps_per_second não existe mais diretamente em bpy.context.scene.rigidbody_world em versões mais recentes do Blender.
Para alterar o número de passos por segundo e iterações do solver da simulação física, você deve acessar o objeto cache dentro do rigidbody_world.
Se desejar posso ajudar a revisar o script completo para compatibilidade! Quer?
User
sim
Assistant
Claro! Aqui está o seu script completo revisado e corrigido para funcionar em versões recentes do Blender, removendo o atributo inexistente steps_per_second e ajustando para funcionar corretamente:
python
User
outro script com mini cubos
Assistant
Claro! Aqui está um script que cria uma pilha grande de mini cubos (muito pequenos), e uma esfera que os derruba. A ideia é gerar centenas de cubos pequenos empilhados para simular um cenário mais detalhado e com muitos objetos físicos.
Script: Pilha de mini cubos com esfera derrubando-os
python
Not yet included in a published release.
import bpy
import mathutils
# Limpa a cena (objetos mesh e empties)
def clear_scene():
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type in {'MESH', 'EMPTY'}:
obj.select_set(True)
bpy.ops.object.delete()
clear_scene()
# Ativa o sistema de física Rigid Body world se não existir
if bpy.context.scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
bpy.context.scene.rigidbody_world.enabled = True
# Parâmetros
cube_size = 1
stack_height = 10
stack_width = 3
stack_depth = 3
gap = 0.01 # pequeno espaço entre cubos para evitar interpenetrações
# Cria a pilha de cubos
cubes = []
start_x = -(stack_width / 2) * (cube_size + gap)
start_y = 0
start_z = cube_size / 2 # para ficar em cima do plano
for i in range(stack_height):
for x in range(stack_width):
for y in range(stack_depth):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (
start_x + x * (cube_size + gap),
start_y + y * (cube_size + gap),
start_z + i * (cube_size + gap)
)
cube.name = f"Cube_{i}_{x}_{y}"
# Adiciona rigid body ativo (ativo = objeto movível)
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cube.rigid_body.friction = 0.5
cube.rigid_body.restitution = 0.1 # pouca elasticidade
cubes.append(cube)
# Cria o solo
bpy.ops.mesh.primitive_plane_add(size=20)
floor = bpy.context.object
floor.location = (0, 0, 0)
floor.name = "Floor"
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE' # objeto estático, não se move
floor.rigid_body.friction = 1
floor.rigid_body.restitution = 0.4
# Cria a esfera que vai derrubar a pilha
bpy.ops.mesh.primitive_uv_sphere_add(radius=cube_size * 1.5)
sphere = bpy.context.object
sphere.name = "Sphere"
# Posiciona a esfera um pouco atrás e acima da pilha para que ela caia e derrube
sphere.location = (0, -5, stack_height * (cube_size + gap) + 5)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.mass = 10
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.friction = 0.5
sphere.rigid_body.restitution = 0.2
# Configura a timeline (frames)
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 250
# Ajuste da câmera para melhor visão
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if cam is None:
bpy.ops.object.camera_add()
cam = bpy.context.object
# Posiciona a câmera em ponto estratégico para enxergar a pilha toda
cam.location = (10, -20, 15)
cam.rotation_euler = (1.1, 0, 0.8)
bpy.context.scene.camera = cam
# Configura a gravidade (padrão do Blender é -9.81)
bpy.context.scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Setup completo! Pressione PLAY no Timeline para assistir a simulação.")
Instruções para uso
Abra o Blender.
Vá em Scripting.
Crie um novo texto e cole todo esse código.
Pressione Run Script.
Na Timeline, pressione Play para rodar a simulação física.
A esfera vai cair derrubando a pilha de cubos.
Se quiser posso ajudar a refinar mais esse script, adicionando:
Texturas ou cores para diferenciar cubos e esfera.
Força inicial na esfera para empurrar lateralmente a pilha.
Ajuste da física para simular melhor colisões.
Fique à vontade para pedir!
import bpy
import random
from mathutils import Vector
# Limpa a cena (todos os mesh, cam, lights)
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Remove também meshes da memória
for block in bpy.data.meshes:
bpy.data.meshes.remove(block)
for block in bpy.data.materials:
bpy.data.materials.remove(block)
clear_scene()
# Cria o mundo Rigid Body se não existir
if bpy.context.scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
bpy.context.scene.rigidbody_world.enabled = True
scene = bpy.context.scene
# Parâmetros
cube_size = 0.8
pyramid_layers = 7
gap = 0.02
# Função para criar material com cor aleatória
def random_colored_material(name="Mat"):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
bsdf = mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs['Base Color'].default_value = [random.random(), random.random(), random.random(), 1]
return mat
# Cria pirâmide de cubos
materials = []
for i in range(pyramid_layers):
layer_materials = [random_colored_material(f"Mat_Layer_{i}_{j}") for j in range(pyramid_layers - i)]
materials.append(layer_materials)
start_x = 0
start_y = 0
start_z = cube_size / 2
for layer in range(pyramid_layers):
cubes_in_layer = pyramid_layers - layer
offset = (cubes_in_layer - 1) * (cube_size + gap) / 2
for x in range(cubes_in_layer):
for y in range(cubes_in_layer):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (
start_x + x * (cube_size + gap) - offset,
start_y + y * (cube_size + gap) - offset,
start_z + layer * (cube_size + gap)
)
cube.name = f"Cube_L{layer}_X{x}_Y{y}"
# Aplica material colorido aleatório
cube.data.materials.append(materials[layer][x % len(materials[layer])])
# Adiciona física
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cube.rigid_body.friction = 0.6
cube.rigid_body.restitution = 0.15
# Cria o plano do chão com material
bpy.ops.mesh.primitive_plane_add(size=30)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 0, 0)
# Material chão cinza
floor_mat = bpy.data.materials.new("Floor_Mat")
floor_mat.use_nodes = True
bsdf = floor_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs['Base Color'].default_value = (0.1, 0.1, 0.16, 1)
bsdf.inputs['Roughness'].default_value = 0.8
floor.data.materials.append(floor_mat)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1
floor.rigid_body.restitution = 0.3
# Cria a esfera que vai derrubar a pilha
bpy.ops.mesh.primitive_uv_sphere_add(radius=cube_size * 1.6)
sphere = bpy.context.object
sphere.name = "Sphere"
sphere.location = (0, -10, pyramid_layers * (cube_size + gap) + 4)
# Material vermelha
sphere_mat = bpy.data.materials.new("Sphere_Mat")
sphere_mat.use_nodes = True
bsdf = sphere_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs['Base Color'].default_value = (1, 0, 0, 1)
sphere.data.materials.append(sphere_mat)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.mass = 15
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.friction = 0.4
sphere.rigid_body.restitution = 0.25
# Configura timeline
scene.frame_start = 1
scene.frame_end = 300
# Posiciona a câmera para visão boa
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if cam is None:
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.location = (15, -25, 20)
cam.rotation_euler = (1.1, 0, 0.9)
scene.camera = cam
# Configura gravidade
scene.rigidbody_world.gravity = (0, 0, -9.81)
# Configuração da animação: aplica velocidade inicial para a esfera lateralmente e para frente
# Precisamos mover a esfera para frente com velocidade na física.
# Como não há suporte direto para velocidade inicial pela API bpy rigidbody,
# podemos usar interation via "Rigid Body Constraint" ou animar a posição.
# Aqui vamos animar a posição para simular lançamento.
sphere.keyframe_insert(data_path="location", frame=1)
sphere.location += Vector((6, 12, -3)) # deslocamento
sphere.keyframe_insert(data_path="location", frame=40)
print("Simulação pronta. Pressione PLAY para ver a animação da bola derrubando a pirâmide.")
Como usar
Cole esse código no Blender em Scripting.
Execute o script.
Vá na timeline e pressione Play.
Você verá a esfera vermelha avançar na direção da pirâmide de cubos coloridos e derrubar a pilha.
Quer ajuda para adicionar mais efeitos, iluminação, ou exportar a animação? Fique à vontade!
import bpy
import random
from mathutils import Vector
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Criar Rigid Body World se não existir
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
# Parâmetros
cube_size = 0.8
wall_width = 10 # cubos na largura
wall_height = 6 # cubos na altura
gap = 0.02
# Criar materiais para cubos (tons de azul)
blue_materials = []
for i in range(5):
mat = bpy.data.materials.new(f"BlueMat{i}")
mat.use_nodes = True
bsdf = mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
color_val = 0.2 + i*0.15
bsdf.inputs['Base Color'].default_value = (0.0, 0.0, color_val, 1)
blue_materials.append(mat)
# Criar a parede
start_x = -(wall_width / 2) * (cube_size + gap)
start_y = 0
start_z = cube_size / 2
for x in range(wall_width):
for z in range(wall_height):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (start_x + x * (cube_size + gap), 0, start_z + z * (cube_size + gap))
# Material aleatório azul
cube.data.materials.append(random.choice(blue_materials))
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 2
cube.rigid_body.friction = 0.6
cube.rigid_body.restitution = 0.05
# Chão
bpy.ops.mesh.primitive_plane_add(size=40)
floor = bpy.context.object
floor.location = (0, 0, 0)
floor.name = "Floor"
floor_mat = bpy.data.materials.new("FloorMat")
floor_mat.use_nodes = True
bsdf = floor_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs['Base Color'].default_value = (0.1, 0.1, 0.1, 1)
bsdf.inputs['Roughness'].default_value = 0.9
floor.data.materials.append(floor_mat)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
floor.rigid_body.restitution = 0.1
# Criar a bola lançada - grande e pesada
bpy.ops.mesh.primitive_uv_sphere_add(radius=2)
sphere = bpy.context.object
sphere.name = "Ball"
sphere.location = (start_x - 8, -3, cube_size * wall_height / 2)
ball_mat = bpy.data.materials.new("BallMat")
ball_mat.use_nodes = True
bsdf = ball_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs['Base Color'].default_value = (1, 0.2, 0.2, 1)
sphere.data.materials.append(ball_mat)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.mass = 50
sphere.rigid_body.friction = 0.4
sphere.rigid_body.restitution = 0.2
# Para controlar velocidade linear, vamos usar um handler que aplica movimentação constante até x-frame
velocity = Vector((20, 0, 0)) # velocidade para frente
max_frame = 60 # aplica essa velocidade até esse frame
def apply_velocity(scene):
frame = scene.frame_current
if frame <= max_frame:
sphere.rigid_body.linear_velocity = velocity
else:
sphere.rigid_body.linear_velocity = Vector((0,0,0))
# Para evitar efeitos indesejados, garantimos que não tenha velocidade angular extra
sphere.rigid_body.angular_velocity = Vector((0,0,0))
# Registra o handler
if apply_velocity not in bpy.app.handlers.frame_change_pre:
bpy.app.handlers.frame_change_pre.append(apply_velocity)
# Configura timeline
scene.frame_start = 1
scene.frame_end = 250
# Posiciona câmera
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if cam is None:
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.location = (15, -20, 15)
cam.rotation_euler = (1.0, 0, 0.75)
scene.camera = cam
# Gravidade
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Setup completo. Use PLAY para ver a bola lançando a parede de cubos e derrubando-a!")
Como usar:
Cole no editor de texto do Blender e execute.
Observe que a bola inicia a esquerda, com velocidade constante para frente.
Ela bate na parede de cubos (parede azul).
A parede reagirá fisicamente e será derrubada.
Pressione PLAY para ver.
Se quiser, posso ajudar com versões mais complexas ou outros tipos de animações! Quer?
import bpy
import random
from mathutils import Vector
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Remove meshes e materiais
for m in bpy.data.meshes:
bpy.data.meshes.remove(m)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Cria Rigid Body World se não existir
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
# Parâmetros
cube_size = 1
stack_height = 7
gap = 0.02
# Cria pilha de cubos
start_x = 0
start_y = 0
start_z = cube_size / 2
for i in range(stack_height):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (start_x, start_y, start_z + i * (cube_size + gap))
cube.name = f"Cube_{i}"
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cube.rigid_body.friction = 0.6
cube.rigid_body.restitution = 0.1
# Chão
bpy.ops.mesh.primitive_plane_add(size=20)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 0, 0)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1
# Cria bola explosiva
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.5)
sphere = bpy.context.object
sphere.name = "Explosive_Sphere"
sphere.location = (-8, 0, 5)
mat_sphere = bpy.data.materials.new("Explosive_Mat")
mat_sphere.use_nodes = True
bsdf = mat_sphere.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs["Base Color"].default_value = (1, 0.2, 0, 1)
bsdf.inputs["Emission"].default_value = (1, 0.4, 0, 5)
sphere.data.materials.append(mat_sphere)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.mass = 20
sphere.rigid_body.friction = 0.4
sphere.rigid_body.restitution = 0.2
# Aplica uma velocidade inicial para lançar a bola
initial_velocity = Vector((15, 0, 2))
def apply_initial_velocity(scene):
frame = scene.frame_current
if frame == 1:
sphere.rigid_body.linear_velocity = initial_velocity
# Remove o handler para não aplicar repetidamente
bpy.app.handlers.frame_change_post.remove(apply_initial_velocity)
bpy.app.handlers.frame_change_post.append(apply_initial_velocity)
# Configura sistema de partículas para explosão
# Cria objeto empty para emitir partículas
bpy.ops.object.empty_add(type='PLAIN_AXES')
emitter = bpy.context.object
emitter.location = sphere.location
emitter.name = "Explosion_Emitter"
# Sistema de partículas (fumaça simples)
ps = emitter.modifiers.new("Explosion_Particles", type='PARTICLE_SYSTEM')
psys = ps.particle_system
psettings = psys.settings
psettings.count = 200
psettings.frame_start = 20 # frame da explosão (ajuste conforme queda)
psettings.frame_end = 21
psettings.lifetime = 50
psettings.emit_from = 'VOLUME'
psettings.physics_type = 'NEWTON'
psettings.render_type = 'HALO'
psettings.gravity = Vector((0, 0, -1))
psettings.use_dynamic_rotation = True
psettings.use_rotations = True
psettings.normal_factor = 3
psettings.factor_random = 2
# Material para partículas - fumaça simples com volume/transparência
mat_particle = bpy.data.materials.new("Particle_Mat")
mat_particle.use_nodes = True
nodes = mat_particle.node_tree.nodes
links = mat_particle.node_tree.links
# Limpa nodes default
for n in nodes:
nodes.remove(n)
# Cria nodes para fumaça básica
output_node = nodes.new(type='ShaderNodeOutputMaterial')
volume_node = nodes.new(type='ShaderNodeVolumePrincipled')
volume_node.inputs["Density"].default_value = 5
volume_node.inputs["Anisotropy"].default_value = 0.7
volume_node.location = (0,0)
links.new(volume_node.outputs["Volume"], output_node.inputs["Volume"])
psettings.material_slot = 0
emitter.data.materials.append(mat_particle)
# Atualiza posição do emissor para acompanhar a esfera (simulação simples)
def update_emitter_pos(scene):
emitter.location = sphere.location
bpy.app.handlers.frame_change_pre.append(update_emitter_pos)
# Configuração da timeline
scene.frame_start = 1
scene.frame_end = 150
# Define câmera
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if cam is None:
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.location = (15, -20, 15)
cam.rotation_euler = (1.1, 0, 0.9)
scene.camera = cam
# Gravidade
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Setup completo. Pressione PLAY para ver a bola explosiva derrubar a pilha de cubos e gerar partículas!")
Como usar
Cole o código no editor de texto do Blender.
Clique em Run Script.
Pressione PLAY na Timeline.
A bola será lançada para frente, derrubará a pilha de cubos e na colisão você verá uma explosão simples de partículas em fumaça.
Se quiser outro tipo de simulação, me avise! Posso fazer scripts com outras físicas, sombras, câmeras dinâmicas etc.
import bpy
import random
from mathutils import Vector
# Limpa a cena
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Cria Rigid Body World se não existir
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
# Parâmetros
cube_size = 1
stack_height = 7
gap = 0.02
# Cria pilha empilhada no eixo X
start_x = 0
start_y = 0
start_z = cube_size / 2
for i in range(stack_height):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (start_x, start_y, start_z + i * (cube_size + gap))
cube.name = f"Cube_{i}"
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cube.rigid_body.friction = 0.8
cube.rigid_body.restitution = 0.9 # alta restituição para quicar
# Cria chão plano
bpy.ops.mesh.primitive_plane_add(size=20)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 0, 0)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1
# Cria a esfera quicante
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.3)
sphere = bpy.context.object
sphere.name = 'Bouncing_Sphere'
sphere.location = (-8, 0, 5)
mat_sphere = bpy.data.materials.new("Sphere_Material")
mat_sphere.use_nodes = True
bsdf = mat_sphere.node_tree.nodes.get('Principled BSDF')
if bsdf:
bsdf.inputs['Base Color'].default_value = (0.2, 0.7, 1.0, 1)
bsdf.inputs['Roughness'].default_value = 0.3
sphere.data.materials.append(mat_sphere)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.mass = 10
sphere.rigid_body.friction = 0.4
sphere.rigid_body.restitution = 0.9 # alta restituição para quicar bastante
# Cria timeline
scene.frame_start = 1
scene.frame_end = 250
# Apply initial velocity - lançando a bola para frente e para cima para quicar
initial_velocity = Vector((20, 0, 10))
def apply_initial_velocity(scene):
if scene.frame_current == 1:
sphere.rigid_body.linear_velocity = initial_velocity
bpy.app.handlers.frame_change_post.remove(apply_initial_velocity)
bpy.app.handlers.frame_change_post.append(apply_initial_velocity)
# Cria câmera com tracking para a esfera
bpy.ops.object.camera_add()
camera = bpy.context.object
camera.name = "TrackingCamera"
# Posiciona a câmera inicial longe e um pouco acima e atrás
camera.location = (0, -15, 10)
scene.camera = camera
# Cria Empty alvo para tracking
bpy.ops.object.empty_add(type='PLAIN_AXES', location=(0,0,0))
target = bpy.context.object
target.name = "CameraTarget"
# Parent target ao sphere para acompanhar movimento
target.parent = sphere
target.location = (0,0,0)
# Adiciona constraint da câmera para olhar para o target
track = camera.constraints.new(type='TRACK_TO')
track.target = target
track.track_axis = 'TRACK_NEGATIVE_Z'
track.up_axis = 'UP_Y'
print("Setup concluído! Pressione PLAY para ver a bola quicando e derrubando os cubos com a câmera seguindo.")
Como usar:
Coloque o script no editor de texto do Blender.
Execute o script.
Aperte PLAY na timeline.
A bola será lançada, quicará com alta restituição (bounce), derrubando os cubos.
A câmera seguirá a bola automaticamente, graças ao constraint TRACK_TO e ao objeto Empty “alvo”.
Se quiser, posso ajudar a adicionar luzes, partículas, ou qualquer outro efeito para enriquecer a cena! Quer?
import bpy
import random
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Limpa dados para evitar lixo na memória
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Cria Rigid Body World se não existir
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
# Parâmetros básicos
cube_size = 1.0
stack_height = 10
sphere_radius = 0.3
num_balls = 15
gap = 0.02
# Cria a pilha de cubos
start_x = 0
start_y = 0
start_z = cube_size / 2
for i in range(stack_height):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (start_x, start_y, start_z + i * (cube_size + gap))
cube.name = f"Cube_{i}"
# Adiciona rigid body ativo
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1.0
cube.rigid_body.friction = 0.5
cube.rigid_body.restitution = 0.2
# Chão
bpy.ops.mesh.primitive_plane_add(size=30)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 0, 0)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
floor.rigid_body.restitution = 0.3
# Materiais
mat_cube = bpy.data.materials.new("CubeMaterial")
mat_cube.diffuse_color = (0.6, 0.6, 0.6, 1)
mat_sphere = bpy.data.materials.new("SphereMaterial")
mat_sphere.diffuse_color = (0.1, 0.6, 1.0, 1)
# Aplica material aos cubos
for obj in bpy.data.objects:
if "Cube" in obj.name:
if len(obj.data.materials) == 0:
obj.data.materials.append(mat_cube)
# Cria várias esferas caindo aleatoriamente acima da pilha
for i in range(num_balls):
bpy.ops.mesh.primitive_uv_sphere_add(radius=sphere_radius)
ball = bpy.context.object
ball.name = f"Ball_{i}"
ball.location = (
random.uniform(-1.5, 1.5), # largura em X próxima da pilha
random.uniform(-1.5, 1.5), # largura em Y próxima da pilha
stack_height * (cube_size + gap) + random.uniform(2, 6) # altura aleatória acima da pilha
)
if len(ball.data.materials) == 0:
ball.data.materials.append(mat_sphere)
# Adiciona rigid body ativo
bpy.ops.rigidbody.object_add()
ball.rigid_body.type = 'ACTIVE'
ball.rigid_body.mass = 0.5
ball.rigid_body.friction = 0.4
ball.rigid_body.restitution = 0.5 # bolas quicam um pouco
# Configura câmera
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if cam is None:
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.location = (10, -15, 15)
cam.rotation_euler = (1.1, 0, 0.85)
scene.camera = cam
# Adiciona luz do Sol
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light_obj = bpy.data.objects.new(name="Sun", object_data=light_data)
scene.collection.objects.link(light_obj)
light_obj.location = (5, -5, 10)
light_obj.rotation_euler = (0.7, 0, 0.7)
# Configura Timeline
scene.frame_start = 1
scene.frame_end = 300
# Configura gravidade
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Simulação pronta! Pressione PLAY para ver várias bolas caindo e derrubando a pilha de cubos.")
Como usar:
Cole o código no editor de texto do Blender.
Execute o script.
Pressione PLAY na Timeline para observar várias bolas caindo sobre a pilha e derrubando os cubos.
Se quiser um script ainda diferente ou mais complexo, me avise!
import bpy
import math
from mathutils import Vector
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Remover meshes e materiais para liberar memória
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Ativa o sistema de física Rigid Body World
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
scene.rigidbody_world.time_scale = 1.0
# Criar rampa inclinada
bpy.ops.mesh.primitive_plane_add(size=15)
ramp = bpy.context.object
ramp.name = "Ramp"
ramp.rotation_euler = (math.radians(-25), 0, 0) # inclinação negativa 25 graus
ramp.location = (0, 0, 0)
bpy.ops.rigidbody.object_add()
ramp.rigid_body.type = 'PASSIVE'
ramp.rigid_body.friction = 1.0
ramp.rigid_body.restitution = 0.2
# Cria chão plano para ficar à frente da rampa
bpy.ops.mesh.primitive_plane_add(size=30)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 14, -1)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
floor.rigid_body.restitution = 0.2
# Pilha de cubos em cima da rampa (colocados calculando posição considerando inclinação)
cube_size = 1.0
stack_height = 6
stack_width = 3
stack_depth = 2
gap = 0.02
# Vetor de inclinação para subir rampa
incline_angle = math.radians(25)
z_offset_per_layer = cube_size * math.cos(incline_angle)
y_offset_per_layer = cube_size * math.sin(incline_angle)
base_x = 0
base_y = -2
base_z = cube_size / 2 + (cube_size / 2) * math.cos(incline_angle)
for h in range(stack_height):
for i in range(stack_width):
for j in range(stack_depth):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
# Posiciona cubos na rampa levando em conta inclinação
cube.location = (
base_x + (i - stack_width / 2) * (cube_size + gap),
base_y + j * (cube_size + gap) + h * y_offset_per_layer,
base_z + h * z_offset_per_layer
)
cube.name = f"Cube_{h}_{i}_{j}"
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1.0
cube.rigid_body.friction = 0.8
cube.rigid_body.restitution = 0.1
# Cria esfera no topo para rolar rampa
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.2)
sphere = bpy.context.object
sphere.name = "RollingBall"
# Posiciona no topo da rampa, um pouco acima da pilha para garantir contato inicial
sphere.location = (0, -5.5, cube_size * stack_height * math.cos(incline_angle) + 3)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.mass = 15
sphere.rigid_body.friction = 0.5
sphere.rigid_body.restitution = 0.3
# Configura timeline
scene.frame_start = 1
scene.frame_end = 350
# Define gravidade
scene.rigidbody_world.gravity = (0, 0, -9.81)
# Câmera com animação para acompanhar rampa
bpy.ops.object.camera_add()
camera = bpy.context.object
camera.name = "Camera"
camera.location = (10, -12, 8)
camera.rotation_euler = (math.radians(60), 0, math.radians(45))
scene.camera = camera
# Adiciona target empty para usar TRACK_TO constraint
bpy.ops.object.empty_add(type='PLAIN_AXES')
target = bpy.context.object
target.name = "CameraTarget"
target.location = sphere.location
# Constraint de câmera para olhar para bola
constraint = camera.constraints.new(type='TRACK_TO')
constraint.target = target
constraint.track_axis = 'TRACK_NEGATIVE_Z'
constraint.up_axis = 'UP_Y'
# Função de atualização para mover o target junto com a bola e animar a câmera levemente
def camera_follow(scene):
target.location = sphere.location
frame = scene.frame_current
# Animação suave de zoom lateral da câmera
camera.location.x = 10 + 2 * math.sin(frame * 0.05)
camera.location.y = -12 + 2 * math.cos(frame * 0.05)
# Registra o handler (remove se estiver registrado para evitar duplicação)
handlers = bpy.app.handlers.frame_change_pre
for h in handlers:
if h.__name__ == "camera_follow":
handlers.remove(h)
bpy.app.handlers.frame_change_pre.append(camera_follow)
print("Setup completo! Pressione PLAY para ver a bola rolar a rampa e derrubar os cubos com câmera dinâmica.")
Como usar
Copie e cole este script no editor de texto do Blender.
Execute o script.
Pressione PLAY na timeline.
Veja a bola rolar rampa abaixo, derrubando a pilha de cubos. A câmera acompanha a bola com uma leve animação de movimento.
Se quiser outras ideias diferentes ou mais detalhes como iluminação, efeitos de partículas etc., é só avisar!
import bpy
import math
from mathutils import Vector, Euler
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Ativa o sistema de física Rigid Body World
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
# Cria pilha de cubos no chão
cube_size = 1.0
stack_height = 8
gap = 0.02
for i in range(stack_height):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (0, 0, cube_size/2 + i*(cube_size+gap))
cube.name = f"Cube_{i}"
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1.0
cube.rigid_body.friction = 0.6
cube.rigid_body.restitution = 0.1
# Chão
bpy.ops.mesh.primitive_plane_add(size=30)
floor = bpy.context.object
floor.location = (0, 0, 0)
floor.name = "Floor"
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
# Cria tubo transparente (4 planos laterais formando tubo quadrado)
tube_height = cube_size * stack_height + 5
tube_radius = 2
thickness = 0.1
# Função material vidro transparente
def make_glass_material(name="GlassMaterial"):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
# Clear default nodes
for n in nodes:
nodes.remove(n)
output = nodes.new(type='ShaderNodeOutputMaterial')
glass = nodes.new(type='ShaderNodeBsdfGlass')
glass.inputs['IOR'].default_value = 1.45
glass.location = (0,0)
output.location = (200,0)
links.new(glass.outputs['BSDF'], output.inputs['Surface'])
return mat
glass_mat = make_glass_material()
# Cria os planos do tubo
def create_wall(location, rotation):
bpy.ops.mesh.primitive_plane_add(size=tube_radius*2)
wall = bpy.context.object
wall.location = location
wall.rotation_euler = rotation
wall.scale.x = tube_radius
wall.scale.y = thickness
wall.data.materials.append(glass_mat)
bpy.ops.rigidbody.object_add()
wall.rigid_body.type = 'PASSIVE'
wall.rigid_body.friction = 0.1
wall.rigid_body.restitution = 0.05
wall.name = "TubeWall"
return wall
# Frente
create_wall(location=(0, tube_radius, tube_height/2), rotation=Euler((0,0,0), 'XYZ'))
# Trás
create_wall(location=(0, -tube_radius, tube_height/2), rotation=Euler((0,0,0), 'XYZ'))
# Esquerda
create_wall(location=(-tube_radius, 0, tube_height/2), rotation=Euler((0,0,math.radians(90)), 'XYZ'))
# Direita
create_wall(location=(tube_radius, 0, tube_height/2), rotation=Euler((0,0,math.radians(90)), 'XYZ'))
# Cria esfera lançada de cima dentro do tubo
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.2)
sphere = bpy.context.object
sphere.name = "RollingSphere"
sphere.location = (0, 0, tube_height + 2)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.mass = 20
sphere.rigid_body.friction = 0.4
sphere.rigid_body.restitution = 0.3
# Configura timeline
scene.frame_start = 1
scene.frame_end = 300
# Define gravidade
scene.rigidbody_world.gravity = (0, 0, -9.81)
# Câmera posicionada para melhor visão
bpy.ops.object.camera_add()
camera = bpy.context.object
camera.name = "Camera"
camera.location = (10, -15, tube_height / 2)
camera.rotation_euler = (math.radians(70), 0, math.radians(40))
scene.camera = camera
print("Script completo! Pressione PLAY para ver a animação da bola dentro do tubo derrubando a pilha de cubos.")
Como usar:
Cole esse script no editor de texto do Blender.
Execute.
Pressione PLAY para assistir a bola caindo dentro do tubo transparente e derrubando a pilha.
Se quiser outras ideias criativas ou animações procedurais, me avise!
import bpy
import math
from mathutils import Vector
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# Remove meshes e materiais para evitar lixo
for m in bpy.data.meshes:
bpy.data.meshes.remove(m)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Ativa sistema de física Rigid Body World
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
# Cria chão
bpy.ops.mesh.primitive_plane_add(size=40)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 0, 0)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
# Parâmetros da pilha cubos
cube_size = 1
stack_height = 8
gap = 0.02
base_x = 0
base_y = 0
base_z = cube_size / 2
# Cria pilha de cubos empilhados verticalmente
for i in range(stack_height):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (base_x, base_y, base_z + i * (cube_size + gap))
cube.name = f"Cube_{i}"
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1.5
cube.rigid_body.friction = 0.6
cube.rigid_body.restitution = 0.1
# Cria pendulos: esferas penduradas em torno da pilha, que vão oscilar e bater na pilha
num_pendulums = 5
radius = 8
string_length = 6
ball_radius = 1
pendulum_collection = bpy.data.collections.new("Pendulums")
scene.collection.children.link(pendulum_collection)
for i in range(num_pendulums):
angle = (2*math.pi / num_pendulums)*i
# Empty para suporte fixo (pivot)
bpy.ops.object.empty_add(type='PLAIN_AXES')
pivot = bpy.context.object
pivot.name = f"Pivot_{i}"
pivot.location = (radius * math.cos(angle), radius * math.sin(angle), string_length + ball_radius + 4)
pendulum_collection.objects.link(pivot)
scene.collection.objects.unlink(pivot)
# Bola pendulo
bpy.ops.mesh.primitive_uv_sphere_add(radius=ball_radius)
ball = bpy.context.object
ball.name = f"Pendulum_Ball_{i}"
ball.location = (pivot.location.x, pivot.location.y, pivot.location.z - string_length)
pendulum_collection.objects.link(ball)
scene.collection.objects.unlink(ball)
# Rigidbody bola ativa
bpy.ops.rigidbody.object_add()
ball.rigid_body.type = 'ACTIVE'
ball.rigid_body.mass = 10
ball.rigid_body.friction = 0.4
ball.rigid_body.restitution = 0.2
# Conecta bola ao pivot via rigid body constraint do tipo rigid (pode usar "hinge" mas menos estável)
bpy.ops.object.select_all(action='DESELECT')
ball.select_set(True)
pivot.select_set(True)
bpy.context.view_layer.objects.active = pivot
bpy.ops.rigidbody.constraint_add(type='GENERIC')
constraint = bpy.context.object.rigid_body_constraint
constraint.object1 = pivot
constraint.object2 = ball
# Limita movimentos para simular fio do pêndulo
constraint.use_limit_ang_x = True
constraint.limit_ang_x_lower = -0.5
constraint.limit_ang_x_upper = 0.5
constraint.use_limit_ang_y = True
constraint.limit_ang_y_lower = -0.5
constraint.limit_ang_y_upper = 0.5
constraint.use_limit_ang_z = True
constraint.limit_ang_z_lower = 0
constraint.limit_ang_z_upper = 0
constraint.use_limit_lin_x = True
constraint.limit_lin_x_lower = 0
constraint.limit_lin_x_upper = 0
constraint.use_limit_lin_y = True
constraint.limit_lin_y_lower = 0
constraint.limit_lin_y_upper = 0
constraint.use_limit_lin_z = True
constraint.limit_lin_z_lower = 0
constraint.limit_lin_z_upper = 0
# Animação inicial: dar impulso lateral na primeira bola para começar o movimento
def impulse_pendulum(scene):
frame = scene.frame_current
if frame == 1:
ball = bpy.data.objects.get("Pendulum_Ball_0")
if ball:
ball.rigid_body.linear_velocity = Vector((10, 0, 0))
bpy.app.handlers.frame_change_post.remove(impulse_pendulum)
bpy.app.handlers.frame_change_post.append(impulse_pendulum)
# Configura timeline
scene.frame_start = 1
scene.frame_end = 300
# Configura câmera
bpy.ops.object.camera_add()
camera = bpy.context.object
camera.location = (25, -25, 25)
camera.rotation_euler = (math.radians(45), 0, math.radians(45))
scene.camera = camera
# Gravidade normal
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Setup finalizado! Aperte PLAY para ver os pêndulos oscilarem e derrubarem a pilha de cubos.")
Como usar:
Cole no editor de texto do Blender e execute.
Pressione PLAY para rodar a simulação física.
Observe os pêndulos oscilando e derrubando a pilha de cubos.
Quer mais algum estilo diferente ou funcionalidade extra? É só pedir!
import bpy
import math
from mathutils import Vector, Euler
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Ativa sistema de física Rigid Body World
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
scene.rigidbody_world.time_scale = 1.0
scene.rigidbody_world.steps_per_second = 250
scene.rigidbody_world.solver_iterations = 30
# Criar material simples
def create_material(name, base_color):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
bsdf = mat.node_tree.nodes.get("Principled BSDF")
bsdf.inputs['Base Color'].default_value = base_color
bsdf.inputs['Roughness'].default_value = 0.5
return mat
mat_ramp = create_material("Ramp_Material", (0.6, 0.4, 0.2, 1))
mat_ball = create_material("Ball_Material", (1, 0.1, 0.1, 1))
mat_pivot = create_material("Pivot_Material", (0.1, 0.1, 0.1, 1))
mat_box = create_material("Box_Material", (0.2, 0.5, 1, 1))
mat_cube = create_material("Cube_Material", (0.8, 0.8, 0.3, 1))
mat_floor = create_material("Floor_Material", (0.4, 0.4, 0.4, 1))
# --- Cria chão ---
bpy.ops.mesh.primitive_plane_add(size=60)
floor = bpy.context.object
floor.location = (0, 0, 0)
floor.name = "Floor"
floor.data.materials.append(mat_floor)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
floor.rigid_body.restitution = 0.1
# --- Cria rampa ---
bpy.ops.mesh.primitive_plane_add(size=20)
ramp = bpy.context.object
ramp.name = "Ramp"
ramp.location = (-10, 0, 0)
ramp.rotation_euler = (math.radians(-25), 0, 0)
ramp.data.materials.append(mat_ramp)
bpy.ops.rigidbody.object_add()
ramp.rigid_body.type = 'PASSIVE'
ramp.rigid_body.friction = 0.8
ramp.rigid_body.restitution = 0.05
# --- Cria esfera (bola) para rolar rampa ---
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.2)
ball = bpy.context.object
ball.name = "Ball"
ball.location = (-15, 0, 7)
ball.data.materials.append(mat_ball)
bpy.ops.rigidbody.object_add()
ball.rigid_body.type = 'ACTIVE'
ball.rigid_body.mass = 10
ball.rigid_body.friction = 0.5
ball.rigid_body.restitution = 0.3
# Aplica velocidade para a bola descer a rampa
def apply_ball_velocity(scene):
if scene.frame_current == 1:
ball.rigid_body.linear_velocity = Vector((10, 0, 0))
bpy.app.handlers.frame_change_post.remove(apply_ball_velocity)
bpy.app.handlers.frame_change_post.append(apply_ball_velocity)
# --- Cria pivô balanço (gangorra) ---
# Cria barra
bpy.ops.mesh.primitive_cube_add(size=0.5, scale=(6, 0.5, 0.25))
pivot_bar = bpy.context.object
pivot_bar.name = "Pivot_Bar"
pivot_bar.location = (0, 0, 1.25)
pivot_bar.data.materials.append(mat_pivot)
bpy.ops.rigidbody.object_add()
pivot_bar.rigid_body.type = 'ACTIVE'
pivot_bar.rigid_body.mass = 5
pivot_bar.rigid_body.friction = 0.5
pivot_bar.rigid_body.restitution = 0.2
# Cria suporte fixo (base da gangorra)
bpy.ops.mesh.primitive_cylinder_add(radius=0.6, depth=1)
pivot_base = bpy.context.object
pivot_base.name = "Pivot_Base"
pivot_base.location = (0, 0, 0.75)
pivot_base.data.materials.append(mat_pivot)
bpy.ops.rigidbody.object_add()
pivot_base.rigid_body.type = 'PASSIVE'
pivot_base.rigid_body.friction = 0.8
# Constraint pêndulo para a barra no suporte
bpy.ops.object.select_all(action='DESELECT')
pivot_bar.select_set(True)
pivot_base.select_set(True)
bpy.context.view_layer.objects.active = pivot_base
bpy.ops.rigidbody.constraint_add(type='HINGE')
constraint = bpy.context.object.rigid_body_constraint
constraint.object1 = pivot_base
constraint.object2 = pivot_bar
constraint.use_limit_ang_z = True
constraint.limit_ang_z_lower = math.radians(-45)
constraint.limit_ang_z_upper = math.radians(45)
constraint.use_motor_ang = False
# --- Caixa no lado da gangorra (lado oposto a bola) ---
bpy.ops.mesh.primitive_cube_add(size=2)
box = bpy.context.object
box.name = "Box"
box.location = (5, 0, 3)
box.data.materials.append(mat_box)
bpy.ops.rigidbody.object_add()
box.rigid_body.type = 'ACTIVE'
box.rigid_body.mass = 8
box.rigid_body.friction = 0.6
box.rigid_body.restitution = 0.2
# --- Pilha piramidal de cubos que será derrubada ---
cube_size = 1.0
pyramid_layers = 6
gap = 0.02
start_x = 15
start_y = -((pyramid_layers) * (cube_size + gap)) / 2
start_z = cube_size / 2
for layer in range(pyramid_layers):
cubes_in_layer = pyramid_layers - layer
offset = (cubes_in_layer - 1) * (cube_size + gap) / 2
for x in range(cubes_in_layer):
for y in range(cubes_in_layer):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (
start_x + x * (cube_size + gap) - offset,
start_y + y * (cube_size + gap),
start_z + layer * (cube_size + gap)
)
cube.data.materials.append(mat_cube)
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cube.rigid_body.friction = 0.5
cube.rigid_body.restitution = 0.15
# Constrói constraint para empurrar a caixa quando bala tocar barra
# Criar sensor invisível para detectar contato (prox. à barra, lado bola)
bpy.ops.mesh.primitive_cube_add(size=1.5)
sensor = bpy.context.object
sensor.name = "Sensor"
sensor.location = (-2, 0, 1.5)
sensor.display_type = 'WIRE'
sensor.hide_render = True
sensor.hide_viewport = True
bpy.ops.rigidbody.object_add()
sensor.rigid_body.type = 'PASSIVE'
sensor.rigid_body.collision_shape = 'BOX'
# Configura colisão com o sensor para aplicar impulso na caixa - via handler simples
def sensor_impulse(scene):
# Pegamos proximidade aproximada (simplificado pois API não tem evento direto)
dist = (pivot_bar.location - sensor.location).length
ball_dist = (ball.location - sensor.location).length
# Quando bola estiver próximo do sensor, aplica impulso na caixa para simular empurrão
if scene.frame_current > 10 and ball_dist < 2.5:
box.rigid_body.velocity.x += 10
bpy.app.handlers.frame_change_pre.remove(sensor_impulse)
bpy.app.handlers.frame_change_pre.append(sensor_impulse)
# --- Configura câmera animada para acompanhar a ação ---
bpy.ops.object.camera_add()
camera = bpy.context.object
camera.name = "Camera"
camera.location = (-20, -30, 20)
camera.rotation_euler = Euler((math.radians(55), 0, math.radians(45)), 'XYZ')
scene.camera = camera
def animate_camera(scene):
frame = scene.frame_current
# Pequena rotação suave nos frames para dar movimento
camera.location.x = -20 + math.sin(frame * 0.03) * 5
camera.location.y = -30 + math.cos(frame * 0.015) * 5
camera.location.z = 20 + math.sin(frame * 0.02) * 3
camera.keyframe_insert(data_path="location", frame=frame)
camera.keyframe_insert(data_path="rotation_euler", frame=frame)
# Para evitar cadastrar múltiplos handlers no Blender
handlers = bpy.app.handlers.frame_change_pre
for h in handlers:
if h.__name__ == "animate_camera":
handlers.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_camera)
# --- Configura inserção e tempo do vídeo ---
scene.frame_start = 1
scene.frame_end = 400
# Gravidade padrão
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Cena Rube Goldberg configurada! Pressione PLAY para ver a simulação completa.")
Como usar:
Copie e cole este script no editor de texto do Blender.
Execute o script.
Pressione PLAY para rodar toda a simulação.
Veja a bola descer a rampa, ativar a gangorra, lançar a caixa e derrubar a pilha de cubos.
Se quiser, posso ajudar a expandir a cena com iluminação, partículas, ou controles mais complexos! Quer?
import bpy
import math
from mathutils import Vector, Euler
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Ativa sistema de física Rigid Body World
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
scene.rigidbody_world.time_scale = 1.0
scene.rigidbody_world.solver_iterations = 30
# scene.rigidbody_world.point_cache.frame_step = 1 # opcional, não obrigatório
# Criar material simples
def create_material(name, base_color):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
bsdf = mat.node_tree.nodes.get("Principled BSDF")
bsdf.inputs['Base Color'].default_value = base_color
bsdf.inputs['Roughness'].default_value = 0.5
return mat
mat_ramp = create_material("Ramp_Material", (0.6, 0.4, 0.2, 1))
mat_ball = create_material("Ball_Material", (1, 0.1, 0.1, 1))
mat_pivot = create_material("Pivot_Material", (0.1, 0.1, 0.1, 1))
mat_box = create_material("Box_Material", (0.2, 0.5, 1, 1))
mat_cube = create_material("Cube_Material", (0.8, 0.8, 0.3, 1))
mat_floor = create_material("Floor_Material", (0.4, 0.4, 0.4, 1))
# --- Cria chão ---
bpy.ops.mesh.primitive_plane_add(size=60)
floor = bpy.context.object
floor.location = (0, 0, 0)
floor.name = "Floor"
floor.data.materials.append(mat_floor)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1.0
floor.rigid_body.restitution = 0.1
# --- Cria rampa ---
bpy.ops.mesh.primitive_plane_add(size=20)
ramp = bpy.context.object
ramp.name = "Ramp"
ramp.location = (-10, 0, 0)
ramp.rotation_euler = (math.radians(-25), 0, 0)
ramp.data.materials.append(mat_ramp)
bpy.ops.rigidbody.object_add()
ramp.rigid_body.type = 'PASSIVE'
ramp.rigid_body.friction = 0.8
ramp.rigid_body.restitution = 0.05
# --- Cria esfera (bola) para rolar rampa ---
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.2)
ball = bpy.context.object
ball.name = "Ball"
ball.location = (-15, 0, 7)
ball.data.materials.append(mat_ball)
bpy.ops.rigidbody.object_add()
ball.rigid_body.type = 'ACTIVE'
ball.rigid_body.mass = 10
ball.rigid_body.friction = 0.5
ball.rigid_body.restitution = 0.3
# Aplica velocidade para a bola descer a rampa
def apply_ball_velocity(scene):
if scene.frame_current == 1:
ball.rigid_body.linear_velocity = Vector((10, 0, 0))
bpy.app.handlers.frame_change_post.remove(apply_ball_velocity)
bpy.app.handlers.frame_change_post.append(apply_ball_velocity)
# --- Cria pivô balanço (gangorra) ---
# Cria barra
bpy.ops.mesh.primitive_cube_add(size=0.5, scale=(6, 0.5, 0.25))
pivot_bar = bpy.context.object
pivot_bar.name = "Pivot_Bar"
pivot_bar.location = (0, 0, 1.25)
pivot_bar.data.materials.append(mat_pivot)
bpy.ops.rigidbody.object_add()
pivot_bar.rigid_body.type = 'ACTIVE'
pivot_bar.rigid_body.mass = 5
pivot_bar.rigid_body.friction = 0.5
pivot_bar.rigid_body.restitution = 0.2
# Cria suporte fixo (base da gangorra)
bpy.ops.mesh.primitive_cylinder_add(radius=0.6, depth=1)
pivot_base = bpy.context.object
pivot_base.name = "Pivot_Base"
pivot_base.location = (0, 0, 0.75)
pivot_base.data.materials.append(mat_pivot)
bpy.ops.rigidbody.object_add()
pivot_base.rigid_body.type = 'PASSIVE'
pivot_base.rigid_body.friction = 0.8
# Constraint pêndulo para a barra no suporte
bpy.ops.object.select_all(action='DESELECT')
pivot_bar.select_set(True)
pivot_base.select_set(True)
bpy.context.view_layer.objects.active = pivot_base
bpy.ops.rigidbody.constraint_add(type='HINGE')
constraint = bpy.context.object.rigid_body_constraint
constraint.object1 = pivot_base
constraint.object2 = pivot_bar
constraint.use_limit_ang_z = True
constraint.limit_ang_z_lower = math.radians(-45)
constraint.limit_ang_z_upper = math.radians(45)
constraint.use_motor_ang = False
# --- Caixa no lado da gangorra (lado oposto a bola) ---
bpy.ops.mesh.primitive_cube_add(size=2)
box = bpy.context.object
box.name = "Box"
box.location = (5, 0, 3)
box.data.materials.append(mat_box)
bpy.ops.rigidbody.object_add()
box.rigid_body.type = 'ACTIVE'
box.rigid_body.mass = 8
box.rigid_body.friction = 0.6
box.rigid_body.restitution = 0.2
# --- Pilha piramidal de cubos que será derrubada ---
cube_size = 1.0
pyramid_layers = 6
gap = 0.02
start_x = 15
start_y = -((pyramid_layers) * (cube_size + gap)) / 2
start_z = cube_size / 2
for layer in range(pyramid_layers):
cubes_in_layer = pyramid_layers - layer
offset = (cubes_in_layer - 1) * (cube_size + gap) / 2
for x in range(cubes_in_layer):
for y in range(cubes_in_layer):
bpy.ops.mesh.primitive_cube_add(size=cube_size)
cube = bpy.context.object
cube.location = (
start_x + x * (cube_size + gap) - offset,
start_y + y * (cube_size + gap),
start_z + layer * (cube_size + gap)
)
cube.data.materials.append(mat_cube)
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 1
cube.rigid_body.friction = 0.5
cube.rigid_body.restitution = 0.15
# Constrói constraint para empurrar a caixa quando bola tocar barra
# Criar sensor invisível para detectar contato (prox. à barra, lado bola)
bpy.ops.mesh.primitive_cube_add(size=1.5)
sensor = bpy.context.object
sensor.name = "Sensor"
sensor.location = (-2, 0, 1.5)
sensor.display_type = 'WIRE'
sensor.hide_render = True
sensor.hide_viewport = True
bpy.ops.rigidbody.object_add()
sensor.rigid_body.type = 'PASSIVE'
sensor.rigid_body.collision_shape = 'BOX'
# Configura colisão com o sensor para aplicar impulso na caixa - via handler simples
def sensor_impulse(scene):
ball_dist = (ball.location - sensor.location).length
# Quando bola estiver próximo do sensor, aplica impulso na caixa para simular empurrão
if scene.frame_current > 10 and ball_dist < 2.5:
box.rigid_body.linear_velocity.x += 10
bpy.app.handlers.frame_change_pre.remove(sensor_impulse)
bpy.app.handlers.frame_change_pre.append(sensor_impulse)
# --- Configura câmera animada para acompanhar a ação ---
bpy.ops.object.camera_add()
camera = bpy.context.object
camera.location = (-20, -30, 20)
camera.rotation_euler = Euler((math.radians(55), 0, math.radians(45)), 'XYZ')
scene.camera = camera
def animate_camera(scene):
frame = scene.frame_current
# Pequena rotação suave nos frames para dar movimento
camera.location.x = -20 + math.sin(frame * 0.03) * 5
camera.location.y = -30 + math.cos(frame * 0.015) * 5
camera.location.z = 20 + math.sin(frame * 0.02) * 3
# Remove handler duplicados antes de adicionar
handlers = bpy.app.handlers.frame_change_pre
for h in handlers:
if h.__name__ == "animate_camera":
handlers.remove(h)
bpy.app.handlers.frame_change_pre.append(animate_camera)
# --- Configura inserção e tempo do vídeo ---
scene.frame_start = 1
scene.frame_end = 400
# Gravidade padrão
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Cena Rube Goldberg configurada! Pressione PLAY para ver a simulação completa.")
Observações:
A linha com steps_per_second foi removida pois não é mais válida.
solver_iterations foi mantida.
Foi mantido o sistema de handler para aplicar impulso simulado na caixa.
Handler da câmera animada corrigido para evitar múltiplas inscrições.
Teste e me avise se quiser ajuda para aprimorar ou adicionar recursos!
import bpy
import random
from mathutils import Vector
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
clear_scene()
scene = bpy.context.scene
# Ativa o mundo rígido se não existir
if scene.rigidbody_world is None:
bpy.ops.rigidbody.world_add()
scene.rigidbody_world.enabled = True
scene.rigidbody_world.solver_iterations = 50
# Parâmetros da pilha
mini_cube_size = 0.1
stack_width = 15 # quantidade de cubos em uma linha
stack_depth = 15
stack_height = 10
gap = 0.005
start_x = -(stack_width/2) * (mini_cube_size + gap)
start_y = -(stack_depth/2) * (mini_cube_size + gap)
start_z = mini_cube_size / 2
# Cria mini cubos empilhados
for h in range(stack_height):
for x in range(stack_width):
for y in range(stack_depth):
bpy.ops.mesh.primitive_cube_add(size=mini_cube_size)
cube = bpy.context.object
cube.location = (
start_x + x * (mini_cube_size + gap),
start_y + y * (mini_cube_size + gap),
start_z + h * (mini_cube_size + gap)
)
cube.name = f"MiniCube_{h}_{x}_{y}"
bpy.ops.rigidbody.object_add()
cube.rigid_body.type = 'ACTIVE'
cube.rigid_body.mass = 0.05
cube.rigid_body.friction = 0.6
cube.rigid_body.restitution = 0.05
# Chão
bpy.ops.mesh.primitive_plane_add(size=20)
floor = bpy.context.object
floor.name = "Floor"
floor.location = (0, 0, 0)
bpy.ops.rigidbody.object_add()
floor.rigid_body.type = 'PASSIVE'
floor.rigid_body.friction = 1
# Cria esfera grande para derrubar
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.5)
sphere = bpy.context.object
sphere.name = "BigSphere"
sphere.location = (0, -5, stack_height * (mini_cube_size + gap) + 2)
bpy.ops.rigidbody.object_add()
sphere.rigid_body.type = 'ACTIVE'
sphere.rigid_body.mass = 20
sphere.rigid_body.friction = 0.4
sphere.rigid_body.restitution = 0.2
# Aplica velocidade inicial para a esfera (colidindo com a pilha)
def apply_sphere_velocity(scene):
if scene.frame_current == 1:
sphere.rigid_body.linear_velocity = Vector((0, 12, 0))
bpy.app.handlers.frame_change_post.remove(apply_sphere_velocity)
bpy.app.handlers.frame_change_post.append(apply_sphere_velocity)
# Configura câmera para enxergar tudo
cam = None
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
cam = obj
break
if cam is None:
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.location = (8, -20, 10)
cam.rotation_euler = (1.1, 0, 0.9)
scene.camera = cam
# Configura timeline e gravidade
scene.frame_start = 1
scene.frame_end = 250
scene.rigidbody_world.gravity = (0, 0, -9.81)
print("Cena de mini cubos pronta! Pressione PLAY para ver a simulação.")
Como usar
Cole e execute o script no Blender.
Pressione PLAY para rodar a simulação.
A esfera grande será lançada em direção à pilha de mini cubos e os derrubará.
Se quiser uma versão com cores, iluminação ou partículas, posso ajudar! Quer?