Claro! Vou criar um addon Blender simples que permita:
- Selecionar um objeto com clique do mouse na viewport.
- Definir manualmente a posição da nova origem (via input numérico para coordenadas locais).
- Aplicar a animação de "tecla pressionada" rotacionando o objeto em torno da origem.
Sobre o addon
- Ele terá um painel na aba "Tool" do 3D View.
- O usuário pode clicar no botão "Selecionar Objeto", que entra no modo de seleção com clique do mouse.
- Depois define os valores da posição da origem local (x, y, z).
- Pressiona "Aplicar origem e animação" para o script fazer o que deve.
Código completo do addon
bl_info = {
"name": "Animação Tecla Piano com Origem Manual",
"author": "ChatGPT",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "View3D > Tool Shelf",
"description": "Seleciona objeto clicando, move origem e aplica animação de tecla",
"category": "Animation",
}
import bpy
from bpy.props import FloatVectorProperty, PointerProperty, BoolProperty
from bpy.types import Operator, Panel, PropertyGroup
from mathutils import Vector
from math import radians
# Property Group para armazenar configurações
class PianoAnimProperties(PropertyGroup):
origin_local: FloatVectorProperty(
name="Origem Local",
description="Posição local da nova origem (x, y, z)",
default=(0.0, 0.0, 0.1), # exemplo padrão
subtype='XYZ',
)
select_mode: BoolProperty(
name="Modo Seleção Ativo",
description="Ativa modo de seleção de objeto clicando na viewport",
default=False
)
# Modal Operator para selecionar objeto clicando
class OT_SelectObjectModal(Operator):
bl_idname = "view3d.select_object_modal"
bl_label = "Selecionar Objeto com Clique"
bl_description = "Clique para selecionar um objeto na viewport"
def modal(self, context, event):
props = context.scene.piano_anim_props
if event.type == 'LEFTMOUSE' and event.value == 'PRESS':
# Ray cast para detectar objeto sob o mouse
region = context.region
rv3d = context.region_data
coord = (event.mouse_region_x, event.mouse_region_y)
view_layer = context.view_layer
result, location, normal, index, obj, matrix = context.scene.ray_cast(view_layer.depsgraph, *self.region_2d_to_origin_and_direction(region, rv3d, coord))
if result and obj.type == 'MESH':
context.view_layer.objects.active = obj
obj.select_set(True)
self.report({'INFO'}, f"Objeto selecionado: {obj.name}")
props.select_mode = False
return {'FINISHED'}
else:
self.report({'WARNING'}, "Nenhum objeto selecionado")
props.select_mode = False
return {'CANCELLED'}
elif event.type in {'RIGHTMOUSE', 'ESC'}:
props.select_mode = False
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
if context.area.type == 'VIEW_3D':
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "Este operador deve ser chamado na View3D")
return {'CANCELLED'}
def region_2d_to_origin_and_direction(self, region, rv3d, coord):
# Calcula origem e direção do raio a partir da posição do mouse na viewport
origin = rv3d.view_matrix.inverted().translation
direction = rv3d.view_rotation @ Vector((0.0, 0.0, -1.0))
# Ajuste para usar o método region_2d_to_origin_3d e region_2d_to_vector_3d
# pois eles produzem resultados melhores para o ray cast
try:
from bpy_extras.view3d_utils import region_2d_to_origin_3d, region_2d_to_vector_3d
origin = region_2d_to_origin_3d(region, rv3d, coord)
direction = region_2d_to_vector_3d(region, rv3d, coord)
except ImportError:
pass
return origin, direction
# Operator para aplicar origem e criar animação
class OT_ApplyOriginAndAnimate(Operator):
bl_idname = "object.apply_origin_and_animate"
bl_label = "Aplicar Origem e Animação"
bl_description = "Move a origem, aplica animação de rotação tecla pressionada"
def execute(self, context):
props = context.scene.piano_anim_props
obj = context.view_layer.objects.active
if not obj or obj.type != 'MESH':
self.report({'ERROR'}, "Selecione um objeto mesh válido antes.")
return {'CANCELLED'}
origin_local = Vector(props.origin_local)
# Converter local -> global
origin_world = obj.matrix_world @ origin_local
# Mover o cursor 3D
context.scene.cursor.location = origin_world
# Mudar origem para cursor
bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')
# Criar animação simples
frame_start = context.scene.frame_current
frame_press = frame_start + 9
frame_release = frame_start + 19
# Limpar keyframes anteriores da rotação
obj.animation_data_clear()
# Posição inicial de rotação (sem pressão)
obj.rotation_euler = (0, 0, 0)
obj.keyframe_insert(data_path="rotation_euler", frame=frame_start)
# Rotação pressionada (15 graus no eixo X)
obj.rotation_euler = (radians(-15), 0, 0)
obj.keyframe_insert(data_path="rotation_euler", frame=frame_press)
# Voltar à posição inicial
obj.rotation_euler = (0, 0, 0)
obj.keyframe_insert(data_path="rotation_euler", frame=frame_release)
self.report({'INFO'}, f"Animação aplicada no objeto '{obj.name}'")
return {'FINISHED'}
# Painel no 3DView > Sidebar > Tool tab
class VIEW3D_PT_PianoAnimationPanel(Panel):
bl_label = "Animação Tecla Piano"
bl_idname = "VIEW3D_PT_piano_animation"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Tool"
def draw(self, context):
layout = self.layout
props = context.scene.piano_anim_props
row = layout.row()
if not props.select_mode:
row.operator("view3d.select_object_modal", text="Selecionar Objeto (Clique)")
else:
row.operator("view3d.select_object_modal", text="Cancelar Seleção").cancel = True
layout.label(text="Posição da Origem (local):")
layout.prop(props, "origin_local")
layout.operator("object.apply_origin_and_animate", text="Aplicar Origem e Animação")
obj = context.view_layer.objects.active
if obj:
layout.label(text=f"Objeto ativo: {obj.name}")
else:
layout.label(text="Nenhum objeto selecionado.")
# Registro
classes = (
PianoAnimProperties,
OT_SelectObjectModal,
OT_ApplyOriginAndAnimate,
VIEW3D_PT_PianoAnimationPanel,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.piano_anim_props = PointerProperty(type=PianoAnimProperties)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
del bpy.types.Scene.piano_anim_props
if __name__ == "__main__":
register()
Como usar
- Salve o código acima num arquivo
.py.
- No Blender, vá em Edit > Preferences > Add-ons > Install e selecione o arquivo.
- Ative o addon.
- Abra a aba Tool (na barra lateral da viewport 3D).
- Clique em Selecionar Objeto (Clique) e clique na tecla que quer animar na viewport 3D (objeto com malha).
- Ajuste a posição local da origem no painel.
- Clique em Aplicar Origem e Animação para posicionar a origem e aplicar a animação da tecla pressionada.
Se quiser que eu faça algum ajuste para facilitar o uso, dizer topo dos polos da tecla etc, é só avisar!