Python: Traceback (most recent call last): File "\Text", line 9, in <module>…
- User
Python: Traceback (most recent call last): File "\Text", line 9, in AttributeError: 'Context' object has no attribute 'active_object'
- Assistant
The error message:
AttributeError: 'Context' object has no attribute 'active_object'indicates that the code is trying to access the
active_objectattribute of aContextobject, but that attribute does not exist.Common scenario for this error
This error often happens in Blender Python scripting because the
bpy.contextobject has an attribute calledactive_objectwhich represents the currently active object in the 3D view. But if you're dealing with a different kind ofContextobject, or if you mistakenly reassigncontextto something else, this attribute might not exist.
How to fix it
-
Check where
contextis coming fromUsually, in Blender scripting,
contextis either passed to a function by Blender, or you refer directly tobpy.context.For example, this works:
import bpy active_obj = bpy.context.active_object print(active_obj.name)But if you have a variable
contextthat's notbpy.context, or is some other object, it might lackactive_object. -
Make sure you are using Blender's context
If inside a function, the argument
contextshould be passed by Blender and it should haveactive_object. Example:def execute(self, context): obj = context.active_object print(obj.name)But if you did something like:
context = some_other_context_object obj = context.active_object # some_other_context_object has no attribute active_objectthen that will cause the error.
-
Check spelling and attributes
It's also possible you mistyped the attribute name. The correct attribute is
active_object, notactive_objoractiveObject.
Summary
- Use
bpy.context.active_objectif you're outside of operator functions. - Use the
contextargument passed into Blender operators. - Do not overwrite or redefine
context.
Example of proper usage
import bpy # Access the active object obj = bpy.context.active_object if obj: print("Active object:", obj.name) else: print("No active object.")Or inside an operator:
import bpy class MyOperator(bpy.types.Operator): bl_idname = "object.my_operator" bl_label = "My Operator" def execute(self, context): obj = context.active_object if obj: self.report({'INFO'}, f"Active object: {obj.name}") else: self.report({'WARNING'}, "No active object.") return {'FINISHED'} def register(): bpy.utils.register_class(MyOperator) def unregister(): bpy.utils.unregister_class(MyOperator) if __name__ == "__main__": register()If you provide your code snippet that causes this error, I can help you pinpoint it more precisely.
-
- User
fix to this: import bpy import math
Clear existing objects
bpy.ops.wm.read_factory_settings(use_empty=True)
Create a cube
bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1)) cube = bpy.context.active_object
Create a light source
bpy.ops.object.light_add(type='POINT', location=(5, 5, 5)) light = bpy.context.active_object light.data.energy = 1000
Create a camera
bpy.ops.object.camera_add(location=(5, -5, 5), rotation=(math.radians(60), 0, math.radians(45))) camera = bpy.context.active_object
Set the camera as the active camera
scene = bpy.context.scene scene.camera = camera
Set frame range
scene.frame_start = 1 scene.frame_end = 250
Add keyframes to rotate the cube
cube.rotation_euler[1] = 0 cube.keyframe_insert(data_path="rotation_euler", frame=1) cube.rotation_euler[1] = math.radians(360) cube.keyframe_insert(data_path="rotation_euler", frame=250)
Set render settings
scene.render.engine = 'CYCLES' scene.cycles.samples = 128 scene.render.resolution_x = 1920 scene.render.resolution_y = 1080 scene.render.filepath = '/tmp/blender_render'
Render the animation
bpy.ops.render.render(animation=True)
- Assistant
Your script looks mostly correct for Blender, but sometimes
bpy.context.active_objectcan be unreliable right after certain operators, especially if run in some contexts like background mode or inside some IDEs. If you ever get theAttributeError: 'Context' object has no attribute 'active_object', a common fix is to grab the newly added object directly by the operator's return value or by checkingbpy.context.selected_objectsimmediately after thebpy.ops.*_add(...)calls.Here is your fixed and improved script with these considerations applied:
import bpy import math # Clear existing objects by loading factory settings bpy.ops.wm.read_factory_settings(use_empty=True) # Create a cube and get reference to it bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1)) cube = bpy.context.object # `bpy.context.object` is the last created object # Create a light source and get reference bpy.ops.object.light_add(type='POINT', location=(5, 5, 5)) light = bpy.context.object light.data.energy = 1000 # Create a camera and get reference bpy.ops.object.camera_add(location=(5, -5, 5), rotation=(math.radians(60), 0, math.radians(45))) camera = bpy.context.object # Set the camera as the active camera for the scene scene = bpy.context.scene scene.camera = camera # Set frame range scene.frame_start = 1 scene.frame_end = 250 # Add keyframes to rotate the cube around Y axis cube.rotation_euler[1] = 0 cube.keyframe_insert(data_path="rotation_euler", frame=1) cube.rotation_euler[1] = math.radians(360) cube.keyframe_insert(data_path="rotation_euler", frame=250) # Set render settings scene.render.engine = 'CYCLES' scene.cycles.samples = 128 scene.render.resolution_x = 1920 scene.render.resolution_y = 1080 scene.render.filepath = '/tmp/blender_render' # Render the animation bpy.ops.render.render(animation=True)Key fixes/notes:
- Use
bpy.context.objectimmediately after theprimitive_*_add()orobject_*_add()calls — this holds the newly created object and is more reliable thanactive_object. - Your script assumes it’s run in Blender's built-in scripting context where
bpy.contextbehaves normally. If running headless or from an external script withbpyimported,bpy.contextmay lack expected attributes. - The cube rotation animation and render code is fine.
If you continue to get errors:
- Make sure you run the script inside Blender's Text Editor or as an addon (operator).
- Alternatively, refer to objects by name or track latest created objects via
bpy.context.selected_objects[-1]after creation. - You can also enable the Info log window in Blender to watch executed commands.
If you want me to help adapt this for background rendering or an addon, just ask!
- Use
- User
fix the script: import bpy import math
Clear existing objects by loading factory settings
bpy.ops.wm.read_factory_settings(use_empty=True)
Create a cube and get reference to it
bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1)) cube = bpy.context.object #
bpy.context.objectis the last created objectCreate a light source and get reference
bpy.ops.object.light_add(type='POINT', location=(5, 5, 5)) light = bpy.context.object light.data.energy = 1000
Create a camera and get reference
bpy.ops.object.camera_add(location=(5, -5, 5), rotation=(math.radians(60), 0, math.radians(45))) camera = bpy.context.object
Set the camera as the active camera for the scene
scene = bpy.context.scene scene.camera = camera
Set frame range
scene.frame_start = 1 scene.frame_end = 250
Add keyframes to rotate the cube around Y axis
cube.rotation_euler[1] = 0 cube.keyframe_insert(data_path="rotation_euler", frame=1) cube.rotation_euler[1] = math.radians(360) cube.keyframe_insert(data_path="rotation_euler", frame=250)
Set render settings
scene.render.engine = 'CYCLES' scene.cycles.samples = 128 scene.render.resolution_x = 1920 scene.render.resolution_y = 1080 scene.render.filepath = '/tmp/blender_render'
Render the animation
bpy.ops.render.render(animation=True)
- Assistant
Your script is mostly correct and should work fine when run inside Blender, but here are a few improvements/fixes to ensure it runs without issues:
- Use
bpy.context.view_layer.objects.activeinstead ofbpy.context.objectto get the active object after adding a mesh or object (more explicit). - Make sure to set the animation end frame in the scene (you did that).
- It’s a good practice to update the scene after changes before rendering.
- Make sure the output folder
/tmp/exists on your system or use an existing path. - For better robustness, clear existing objects by deleting them manually instead of
read_factory_settingsbecause it reloads Blender factory preferences and resets everything, which is sometimes drastic. But if you want to keep it, it's fine.
Here is an improved version of your script:
import bpy import math import os # Clear existing objects by removing all first (optional alternative to read_factory_settings) # Uncomment below if you want to delete all objects manually instead of resetting factory settings: ''' bpy.ops.object.select_all(action='SELECT') bpy.ops.object.delete(use_global=False) ''' # Or reset to factory settings with empty scene (your original approach) bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene # Create a cube and get reference to it bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1)) cube = bpy.context.view_layer.objects.active # more explicit # Create a light source and get reference bpy.ops.object.light_add(type='POINT', location=(5, 5, 5)) light = bpy.context.view_layer.objects.active light.data.energy = 1000 # Create a camera and get reference bpy.ops.object.camera_add(location=(5, -5, 5), rotation=(math.radians(60), 0, math.radians(45))) camera = bpy.context.view_layer.objects.active # Set the camera as the active camera for the scene scene.camera = camera # Set frame range scene.frame_start = 1 scene.frame_end = 250 # Add keyframes to rotate the cube around Y axis cube.rotation_euler[1] = 0 cube.keyframe_insert(data_path="rotation_euler", frame=1) cube.rotation_euler[1] = math.radians(360) cube.keyframe_insert(data_path="rotation_euler", frame=250) # Set render settings scene.render.engine = 'CYCLES' scene.cycles.samples = 128 scene.render.resolution_x = 1920 scene.render.resolution_y = 1080 output_path = '/tmp/blender_render' # Change this if needed # Make sure path exists -- create if missing if not os.path.exists(output_path): os.makedirs(output_path) scene.render.filepath = os.path.join(output_path, "frame_") # Update scene before rendering (usually optional) bpy.context.view_layer.update() # Render animation bpy.ops.render.render(animation=True)Key points:
- Used
bpy.context.view_layer.objects.activeto get the newly added active object. - Ensured output path exists before rendering.
- Kept your overall logic.
If you run this script inside Blender's scripting workspace it should work perfectly.
If you get any errors related to missing attributes or objects, it usually means the context isn't set properly (e.g., running this outside Blender or in background mode). In that case, specify more about your use case.
- Use
- User
oque?
- Assistant
Oi! Parece que você pediu para consertar o script Python para Blender, mas ficou confuso com a explicação em inglês. Vou simplificar e passar um script corrigido e funcionando para você, em português:
Script corrigido e explicado (para usar dentro do Blender):
import bpy import math import os # Reinicia o Blender para cena vazia (apaga tudo) bpy.ops.wm.read_factory_settings(use_empty=True) # Pega a cena atual scene = bpy.context.scene # Cria um cubo na posição (0,0,1) bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1)) cube = bpy.context.view_layer.objects.active # objeto ativo é o cubo criado # Cria uma luz ponto na posição (5,5,5) bpy.ops.object.light_add(type='POINT', location=(5, 5, 5)) light = bpy.context.view_layer.objects.active light.data.energy = 1000 # define a potência da luz # Cria uma câmera na posição (5,-5,5) com rotação especificada bpy.ops.object.camera_add(location=(5, -5, 5), rotation=(math.radians(60), 0, math.radians(45))) camera = bpy.context.view_layer.objects.active # Define a câmera criada como câmera ativa da cena scene.camera = camera # Define o intervalo de frames da animação scene.frame_start = 1 scene.frame_end = 250 # Anima o cubo girando no eixo Y cube.rotation_euler[1] = 0 cube.keyframe_insert(data_path="rotation_euler", frame=1) cube.rotation_euler[1] = math.radians(360) cube.keyframe_insert(data_path="rotation_euler", frame=250) # Definições do render scene.render.engine = 'CYCLES' scene.cycles.samples = 128 scene.render.resolution_x = 1920 scene.render.resolution_y = 1080 # Define local para salvar a renderização (pasta /tmp/blender_render) output_path = '/tmp/blender_render' if not os.path.exists(output_path): os.makedirs(output_path) scene.render.filepath = os.path.join(output_path, "frame_") # Renderiza a animação inteira bpy.ops.render.render(animation=True)
O que mudou/resolvido?
- Usei
bpy.context.view_layer.objects.activepara pegar o objeto recém-criado (mais confiável). - Criei a pasta para salvar os arquivos caso ela não exista.
- Mantive a lógica igual, só ajustei detalhes para garantir que funcione.
Se quiser posso te ajudar a rodar passo a passo ou a entender cada parte! Quer?
- Usei
- User
oque esta animação faz?
- Assistant
Essa animação faz o seguinte:
- Um cubo 3D é criado no centro da cena, um pouco elevado no eixo Z (posição (0, 0, 1)).
- O cubo é animado para girar uma volta completa (360 graus) ao redor do eixo Y (vertical) ao longo de 250 frames (quadros).
- Há uma luz do tipo ponto posicionada para iluminar a cena (em (5, 5, 5)) com alta intensidade, para o cubo ficar visível.
- Uma câmera é posicionada olhando para a cena, com ângulo inclinado para capturar o cubo em uma boa perspectiva.
- A cena será renderizada usando o motor Cycles: gera imagens com qualidade de renderização realista.
- A animação toda (os 250 frames) será renderizada e salva na pasta
/tmp/blender_render/, como uma sequência de imagens.
Resumo simples:
Você terá um cubo girando lentamente dentro de uma cena iluminada e capturada por uma câmera, e o Blender vai gerar as imagens dessa animação para você.
Quer que eu explique mais algum detalhe da animação ou do script?
- User
dê exemplos de animação com fisica para loop
- Assistant
Claro! Vou dar alguns exemplos simples de animações em Blender que usam física e são loopáveis (ou seja, que podem ser repetidas continuamente sem "quebrar" a fluidez).
Exemplos de animação com física para loop em Blender
1. Bola quicando infinitamente entre duas paredes
- Uma bola (mesh esfera) cai, quica repetidamente.
- Configurar a simulação física (rigid body) com restituição alta (quique) e colocar paredes para limitar o movimento.
- Ajustar o tempo da simulação para que o último frame termine igual ao primeiro.
Código exemplo simplificado para bola quicando (rigidbody)
import bpy # Limpa tudo bpy.ops.wm.read_factory_settings(use_empty=True) # Cria o plano como base bpy.ops.mesh.primitive_plane_add(size=10, location=(0, 0, 0)) plane = bpy.context.view_layer.objects.active # Torna o plano estático na simulação física plane.rigid_body = bpy.data.scenes["Scene"].rigid_body_world.collection.objects.new('Rigid Body') plane.rigid_body.enabled = True plane.rigid_body.type = 'PASSIVE' # objeto fixo # Cria a bola bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=(0, 0, 5)) ball = bpy.context.view_layer.objects.active # Ativa rigidbody dinâmico na bola ball.rigid_body.enabled = True ball.rigid_body.type = 'ACTIVE' ball.rigid_body.mass = 1 ball.rigid_body.restitution = 0.9 # quique alto # Definir frames da animação bpy.context.scene.frame_start = 1 bpy.context.scene.frame_end = 120 # Ajuste organização da simulação ou bake para conseguir loop suaveNota: Para loop perfeito, a simulação pode precisar ser "baked" e sincronizada para que final e início da animação coincidam.
2. Cubo caindo e balançando suavemente
- Cubo com rigid body que cai sobre um plano e fica balançando.
- Animação renderizada em loop porque o movimento final suaviza e volta ao equilíbrio.
3. Partículas caindo em loop
- Sistema de partículas com gravidade.
- Configurar para emitir um número constante de partículas e reiniciar o sistema para fazer loop.
Dicas para fazer animações físicas em loop:
- Bake a simulação física (menu Physics > Cache) para controlar exatamente rebobinar o movimento.
- Ajuste valores de restituição (elasticidade) para evitar que a energia se dissipe rápido.
- Escolha um intervalo de frames adequado para que o estado final e inicial coincidam (posição, velocidade).
- Use keyframes para controlar forças externas e garantir estabilidade.
- Em simulações complexas, edite curvas e use interpolação "Linear" para evitar pausas.
Se quiser, posso montar um exemplo completo, passo a passo, para um tipo específico de animação física em loop. Quer fazer uma bola quicando ou algo diferente?
- User
outro
- Assistant
Claro! Vamos ver outro exemplo simples de animação física para loop — desta vez, uma simulação de pendulo oscilando com física rígida.
Exemplo 2: Pêndulo oscilando em loop com física rígida
Descrição:
- Um objeto (uma esfera) suspensa por um braço rígido (uma barra/cilindro), como um pêndulo.
- O pêndulo balança para frente e para trás.
- A animação é configurada para ser perfeitamente loopável (pode repetir infinitamente).
Código Python para Blender (exemplo básico):
import bpy import math # Limpa tudo bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene scene.frame_start = 1 scene.frame_end = 120 # Cria a base fixa (barra de onde pendulo irá pendurar) bpy.ops.mesh.primitive_cube_add(size=0.2, location=(0, 0, 2)) base = bpy.context.view_layer.objects.active base.name = 'Base' # Adiciona corpo rígido passivo (fixo) base.rigid_body = base.modifiers.new(type='VERTEX_WEIGHT_EDIT', name='Rigidbody') base.rigid_body.type = 'PASSIVE' # Cria o braço do pêndulo (cilindro) bpy.ops.mesh.primitive_cylinder_add(radius=0.05, depth=2, location=(0, 0, 1)) arm = bpy.context.view_layer.objects.active arm.name = 'Arm' arm.rotation_euler.x = math.radians(90) # Rigid body no braço (ativo - móvel) bpy.ops.rigidbody.object_add() arm.rigid_body.type = 'ACTIVE' arm.rigid_body.mass = 1 # Cria a esfera/pêndulo na ponta do braço bpy.ops.mesh.primitive_uv_sphere_add(radius=0.2, location=(0, 1, 0)) ball = bpy.context.view_layer.objects.active ball.name = 'Ball' bpy.ops.rigidbody.object_add() ball.rigid_body.type = 'ACTIVE' ball.rigid_body.mass = 1 # Conecta o braço à base (constraint rígida tipo HINGE) bpy.ops.rigidbody.constraint_add(type='HINGE') constraint = bpy.context.object constraint.name = "HingeConstraint" constraint.rigid_body_constraint.object1 = base constraint.rigid_body_constraint.object2 = arm constraint.location = base.location # Conecta a esfera ao braço com outro hinge (para pendurar na ponta do braço) bpy.ops.rigidbody.constraint_add(type='HINGE') constraint2 = bpy.context.object constraint2.name = "HingeConstraint2" constraint2.rigid_body_constraint.object1 = arm constraint2.rigid_body_constraint.object2 = ball constraint2.location = ball.location # Posiciona a cena para o começo da animação scene.frame_set(1) arm.rotation_euler.z = math.radians(30) # Desvia o braço para iniciar o swing arm.keyframe_insert(data_path='rotation_euler', frame=1) # E volta ao equilíbrio no frame final, para fechar o loop scene.frame_set(scene.frame_end) arm.rotation_euler.z = math.radians(-30) arm.keyframe_insert(data_path='rotation_euler', frame=scene.frame_end) # NOTA: Para loop perfeito será necessário ajustar curvas com interpolação "Cyclic" e considerar bake da simulação. print("Configurado pêndulo oscilando para animação loopável")
Como funciona esse exemplo:
- O braço e a bola são objetos com física rígida.
- Dois "hinge" (dobradiças) conectam para que o movimento seja restrito à oscilação.
- A animação começa com o braço inclinado e depois oscila entre -30° e +30° no eixo Z.
- Usando keyframes você pode fazer a oscilação acontecer e configurar para que a curva de animação repita em loop suave.
Se quiser, posso ajudar a ajustar o script para rodar totalmente no Blender ou até gerar uma animação pronta com física realista! Quer?
- User
outro
- Assistant
Claro! Aqui vai mais um exemplo de animação com física que pode ser facilmente feita em loop no Blender:
Exemplo 3: Caixa quicando (Rigid Body) — animação em loop
Descrição:
- Uma caixa que quica verticalmente, simulando física com Rigid Body.
- É possível configurar a “energia de quique” (restituição) para que o movimento seja quase eterno (loopável).
- A animação pode ser feita num intervalo de frames em que o movimento inicial e final sejam iguais, criando um loop suave.
Script Python para Blender:
import bpy import math import os # Limpa cena bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene # Configura intervalo de frames scene.frame_start = 1 scene.frame_end = 100 # Cria chao (plano) bpy.ops.mesh.primitive_plane_add(size=10, location=(0, 0, 0)) floor = bpy.context.view_layer.objects.active floor.name = "Chao" # Define chao como objeto estático na simulação (PASSIVE) bpy.ops.rigidbody.object_add() floor.rigid_body.type = 'PASSIVE' # Cria caixa bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 5)) box = bpy.context.view_layer.objects.active box.name = "Caixa" # Ativa rigid body dinâmico (ACTIVE) bpy.ops.rigidbody.object_add() box.rigid_body.type = 'ACTIVE' box.rigid_body.mass = 1 # Aumenta restituição (quique) box.rigid_body.restitution = 0.9 # Ajusta atrito para pouca perda de energia box.rigid_body.friction = 0.1 # Opcional: desliga a gravidade para efeito de queda suave (se quiser) # bpy.context.scene.rigidbody_world.gravity = (0, 0, -9.81) # Você pode simular e depois “bake” para garantir loops suaves. print("Configuração básica pronta. Rode a simulação para ver o quique em loop.")
O que fazer depois:
- Rode a simulação física (pressione
Alt + Ano viewport). - Para criar loop perfeito, você pode “bakear” a simulação física (Physics > Rigid Body World > Cache).
- Ajuste o intervalo de frames para que o movimento no último frame seja igual ao do primeiro.
Se precisar, posso ajudar a editar mais detalhes, criar bake automático via script, configurar câmera, luz, etc. Quer?
- User
outro
- Assistant
Claro! Aqui vai mais um exemplo de animação física para loop, usando um sistema de partículas simples:
Exemplo 4: Partículas caindo em loop contínuo
Descrição:
- Sistema de partículas que emite continuamente pequenas partículas (gotas, poeira, etc).
- As partículas nascem, caem com a gravidade, e desaparecem, com o sistema reiniciando para criar o efeito de loop contínuo.
- Útil para simular chuva, neve, poeira, etc.
Script Python para Blender:
import bpy # Limpa cena bpy.ops.wm.read_factory_settings(use_empty=True) # Cria um plano emissor (pode ser teto ou área de emissão) bpy.ops.mesh.primitive_plane_add(size=5, location=(0, 0, 5)) emitter = bpy.context.view_layer.objects.active emitter.name = "Emissor" # Cria sistema de partículas no emissor psys = emitter.modifiers.new("Particulas", type='PARTICLE_SYSTEM').particle_system settings = psys.settings settings.count = 1000 # número total de partículas settings.frame_start = 1 # quando começam a nascer partículas settings.frame_end = 50 # termina emissão para criar loop settings.lifetime = 50 # tempo de vida de cada partícula settings.emit_from = 'FACE' # partículas saem da superfície do plano settings.physics_type = 'NEWTON' # simula gravidade settings.use_emit_random = True settings.normal_factor = 0 # velocidade inicial - 0 para cair direto settings.gravity = 1 # gravidade padrão # Configurações para loop suave scene = bpy.context.scene scene.frame_start = 1 scene.frame_end = 50 # No final, as partículas desaparecem enquanto o sistema reinicia print("Sistema de partículas configurado para loop de queda.")
Para rodar e ver:
- Execute este script dentro do Blender.
- Faça a timeline rodar de frame 1 até 50.
- As partículas nascem no plano no topo, caem para baixo devido à gravidade e desaparecem no final.
- Como a emissão está limitada a 50 frames, o sistema reinicia o ciclo, criando um loop perfeito.
Se quiser, posso ajudar a aumentar a complexidade (ex: partículas com colisão, vento, etc) ou criar um sistema para loopar outras simulações! Quer?
- User
outro
- Assistant
Claro! Aqui vai mais um exemplo de animação física em loop, desta vez utilizando um sistema simples de mola ("spring") simulando um objeto oscilando:
Exemplo 5: Massa oscilando presa a mola — animação em loop
Descrição:
- Um objeto (esfera ou cubo) preso a uma mola virtual.
- O objeto oscila para frente e para trás como um sistema massa-mola simples.
- A oscilação é animada por keyframes com curva cíclica para criar um loop suave.
Código Python para Blender:
import bpy import math # Limpa a cena bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene scene.frame_start = 1 scene.frame_end = 100 # Cria o objeto (massa) bpy.ops.mesh.primitive_uv_sphere_add(radius=0.5, location=(0, 0, 1)) mass = bpy.context.view_layer.objects.active # Cria um vazio para representar o ponto fixo da mola bpy.ops.object.empty_add(type='PLAIN_AXES', location=(0, 0, 1)) anchor = bpy.context.view_layer.objects.active # Anima a massa oscilando para frente e para trás no eixo X # Frame 1: posição inicial no x=0 mass.location.x = 0 mass.keyframe_insert(data_path="location", frame=1) # Frame 25: desloca para +2 unidades na X (extensão máxima da mola) mass.location.x = 2 mass.keyframe_insert(data_path="location", frame=25) # Frame 50: volta para x=0 (posição de equilíbrio) mass.location.x = 0 mass.keyframe_insert(data_path="location", frame=50) # Frame 75: desloca para -2 unidades na X (extensão máxima oposta) mass.location.x = -2 mass.keyframe_insert(data_path="location", frame=75) # Frame 100: volta para x=0 (final do ciclo) mass.location.x = 0 mass.keyframe_insert(data_path="location", frame=100) # Define interpolação cíclica para loop suave action = mass.animation_data.action for fcurve in action.fcurves: cycles_mod = fcurve.modifiers.new(type='CYCLES') print("Animação de massa oscilando criada! Rode para ver loop.") # Opcional: adicionar visual da mola (curva, linha, etc) para ficar mais claro
Explicação:
- A posição da esfera é animada para se mover para frente e para trás numa trajetória semelhante à mola oscilando.
- Os keyframes estão espaçados para criar o efeito oscilatório completo.
- A interpolação cíclica (modificador de ciclo) faz a animação repetir infinitamente e suavemente.
- Não usa simulação de física real, mas uma animação simples baseada em keyframes que simula física de forma visual fácil.
Quer que eu te ajude a colocar este efeito dentro de uma cena maior ou com física real de mola?
- User
outro
- Assistant
Claro! Aqui vai mais um exemplo de animação física para loop, usando uma simulação simples de fluidos (tipo gotas caindo e se acumulando), mas com um truque para criar loop.
Exemplo 6: Animação de fluido em loop simples — “água pingando”
Descrição:
- Usamos partículas para simular gotas caindo.
- As gotas nascem e caem numa velocidade constante, desaparecendo no final do ciclo.
- No último frame o sistema reinicia funcionando como loop contínuo.
Script para Blender:
import bpy # Limpa a cena bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene # Configura intervalo de frames para loop scene.frame_start = 1 scene.frame_end = 60 # Cria plano emissor de gotas bpy.ops.mesh.primitive_plane_add(size=2, location=(0, 0, 3)) emitter = bpy.context.view_layer.objects.active # Sistema de partículas do tipo 'HAIR' para controlar melhor o loop psys = emitter.modifiers.new("Particles", type='PARTICLE_SYSTEM').particle_system psys.name = "Gotas" settings = psys.settings settings.count = 200 settings.frame_start = 1 settings.frame_end = 30 settings.lifetime = 30 settings.emit_from = 'FACE' settings.physics_type = 'NEWTON' settings.normal_factor = 0 settings.use_render_adaptive = False settings.use_emit_random = True settings.gravity = 1 settings.brownian_factor = 0.1 settings.render_type = 'OBJECT' # Cria uma esfera pequena para ser a gota bpy.ops.mesh.primitive_uv_sphere_add(radius=0.05, location=(0, 0, 3)) drop_obj = bpy.context.view_layer.objects.active drop_obj.name = "Gota" settings.instance_object = drop_obj print("Configuração pronta! Rode a animação para ver gotas caindo em loop.")
Como funciona:
- O emissor solta partículas por 30 frames.
- Cada partícula vive 30 frames caindo.
- A animação total tem 60 frames com o sistema reiniciando após o frame 30, portanto é loopável.
- A gravidade faz as gotas caírem no plano invisível abaixo.
Se quiser animações físicas mais complexas ou outras ideias para loops, posso ajudar também! Quer continuar?