Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

blender 3d: faça um script para animação procedual complexo de sincronismo de iluminação

  1. User

    blender 3d: faça um script para animação procedual complexo de sincronismo de iluminação

  2. Assistant

    Claro! Vou criar um script em Python para Blender que faça uma animação procedural complexa de sincronismo de iluminação. A ideia é que as luzes mudem sua intensidade, cor e posição de forma sincronizada, com variações baseadas em funções matemáticas para criar um efeito dinâmico e interessante.

    Esse script pode ser utilizado no editor de texto do Blender e executado para gerar automaticamente uma animação das luzes.


    Script: Animação Procedural Complexa de Sincronismo de Iluminação

    import bpy
    import math
    import random
    
    # Parâmetros da animação
    frame_start = 1
    frame_end = 250
    bpy.context.scene.frame_start = frame_start
    bpy.context.scene.frame_end = frame_end
    
    # Função para limpar luzes existentes
    def clear_lights():
        for obj in bpy.data.objects:
            if obj.type == 'LIGHT':
                bpy.data.objects.remove(obj, do_unlink=True)
    
    clear_lights()
    
    # Cria uma coleção para as luzes
    if "Lights" in bpy.data.collections:
        lights_collection = bpy.data.collections["Lights"]
    else:
        lights_collection = bpy.data.collections.new("Lights")
        bpy.context.scene.collection.children.link(lights_collection)
    
    # Parâmetros das luzes
    num_lights = 5
    radius = 5
    
    lights = []
    
    # Cria as luzes distribuídas em círculo
    for i in range(num_lights):
        angle = (2 * math.pi / num_lights) * i
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = 2
    
        # Cria luz
        light_data = bpy.data.lights.new(name=f"Light_{i}", type='POINT')
        light_data.energy = 1000
        light_data.color = (1, 1, 1)
    
        light_obj = bpy.data.objects.new(name=f"Light_{i}", object_data=light_data)
        light_obj.location = (x, y, z)
        lights_collection.objects.link(light_obj)
        lights.append(light_obj)
    
    # Funções de variação
    def intensity_func(frame, idx):
        # Intensidade varia com uma combinação senoidal e ruído
        return 500 + 500 * math.sin(frame * 0.1 + idx * 2) + 200 * math.sin(frame * 0.05 * (idx+1) )
    
    def color_func(frame, idx):
        # Color shifts com hue cycling
        hue = (frame * 0.02 + idx * 0.2) % 1.0
        return hsv_to_rgb(hue, 1, 1)
    
    def position_func(frame, idx):
        # Luz oscila em Z e circula em x,y lentamente
        base_angle = (2 * math.pi / num_lights) * idx
        angle = base_angle + 0.02 * frame
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = 2 + math.sin(frame * 0.1 + idx) * 1.5
        return (x, y, z)
    
    # Conversão HSV para RGB (valores 0-1)
    def hsv_to_rgb(h, s, v):
        import colorsys
        return colorsys.hsv_to_rgb(h, s, v)
    
    # Aplica keyframes ao longo da timeline
    for frame in range(frame_start, frame_end +1):
        bpy.context.scene.frame_set(frame)
        for idx, light in enumerate(lights):
            # Atualiza intensidade (energy)
            energy = intensity_func(frame, idx)
            light.data.energy = energy
            light.data.keyframe_insert(data_path="energy", frame=frame)
    
            # Atualiza cor
            color = color_func(frame, idx)
            light.data.color = color
            light.data.keyframe_insert(data_path="color", frame=frame)
    
            # Atualiza posição
            loc = position_func(frame, idx)
            light.location = loc
            light.keyframe_insert(data_path="location", frame=frame)
    
    print("Animação procedural de sincronismo de iluminação criada com sucesso!")
    

    Como usar:

    1. Abra o Blender (recomendo a versão 3.x).
    2. Vá no Editor de Texto, crie um novo arquivo e cole o script.
    3. Clique em "Run Script".
    4. A animação estará criada na timeline (1 a 250 frames).
    5. Visualize a animação para ver as luzes circulando em torno do centro, mudando de cor e intensidade de forma sincronizada, criando um efeito dinâmico.

    Se quiser mais variações, posso ajudar a adicionar efeitos de flicker aleatório, sincronismo com objetos, ou efeitos mais complexos usando drivers ou nodes. Quer?

  3. User

    outro

  4. Assistant

    Claro! Vou criar outro script para uma animação procedural de sincronismo de iluminação, mas com uma abordagem diferente — desta vez usando várias luzes com padrões de pulso sincronizados por ondas senoidais com diferentes frequências e fases, além de movimentação em espiral e variações de cor usando Gradientes HSV.


    Script 2: Iluminação Sincronizada com Pulsos Senóides e Movimento em Espiral

    import bpy
    import math
    import colorsys
    
    # Reset da cena (opcional, limpa luzes existentes)
    def clear_lights():
        for obj in bpy.data.objects:
            if obj.type == 'LIGHT':
                bpy.data.objects.remove(obj, do_unlink=True)
    
    clear_lights()
    
    # Configurações da animação
    frame_start = 1
    frame_end = 300
    bpy.context.scene.frame_start = frame_start
    bpy.context.scene.frame_end = frame_end
    
    num_lights = 8
    max_radius = 6
    height_amplitude = 3
    
    # Cria coleção para as luzes
    col_name = "SyncLights"
    if col_name in bpy.data.collections:
        col = bpy.data.collections[col_name]
    else:
        col = bpy.data.collections.new(col_name)
        bpy.context.scene.collection.children.link(col)
    
    lights = []
    
    # Criação das luzes
    for i in range(num_lights):
        light_data = bpy.data.lights.new(f"PulseLight_{i}", type='SPOT')
        light_data.energy = 800
        light_data.spot_size = math.radians(45)
        light_data.use_shadow = True
        light_data.color = (1, 1, 1)
    
        light_obj = bpy.data.objects.new(f"PulseLight_{i}", light_data)
        col.objects.link(light_obj)
        lights.append(light_obj)
    
    # Funções de controle:
    
    def pulse_energy(frame, idx):
        # Pulso com frequência e fase diferentes para cada luz
        freq = 0.15 + idx * 0.05
        phase = idx * (math.pi / 4)
        base = 400
        amplitude = 600
        val = base + amplitude * max(0, math.sin(freq * frame + phase))
        return val
    
    def spiral_position(frame, idx):
        # Movimento em espiral para cada luz
        angle = frame * 0.05 + idx * (2 * math.pi / num_lights)
        radius = (max_radius / frame_end) * frame  # Aumenta o raio progressivamente
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = height_amplitude * math.sin(0.1 * frame + idx)
        return (x, y, z)
    
    def gradient_color(frame, idx):
        # Muda o hue no espaço HSV ao longo do tempo
        base_hue = (frame * 0.008 + idx / num_lights) % 1.0
        r, g, b = colorsys.hsv_to_rgb(base_hue, 0.8, 1.0)
        return (r, g, b)
    
    # Keyframing a animação
    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
    
        for idx, light in enumerate(lights):
            # Atualiza energia
            e = pulse_energy(frame, idx)
            light.data.energy = e
            light.data.keyframe_insert(data_path="energy", frame=frame)
    
            # Atualiza posição
            pos = spiral_position(frame, idx)
            light.location = pos
            light.keyframe_insert(data_path="location", frame=frame)
    
            # Aponta luz para o centro (opcional)
            direction = (-pos[0], -pos[1], -pos[2])
            light.rotation_euler = direction_to_euler(direction)
            light.keyframe_insert(data_path="rotation_euler", frame=frame)
    
            # Atualiza cor
            c = gradient_color(frame, idx)
            light.data.color = c
            light.data.keyframe_insert(data_path="color", frame=frame)
    
    print("Animação com pulsos em sincronismo e movimento em espiral criada!")
    
    # --- Função auxiliar para orientar a luz ---
    def direction_to_euler(direction):
        # Converte um vetor direção para Euler (aponta o eixo negativo Z do objeto para a direção)
        import mathutils
        vec = mathutils.Vector(direction)
        vec.normalize()
        # A luz padrão aponta para -Z localmente, então rotacionamos para alinhá-la com vec
        rot_quat = vec.to_track_quat('-Z', 'Y')
        return rot_quat.to_euler()
    

    Como usar:

    1. No Blender, abra o Editor de Texto, cole o script.
    2. Execute o script.
    3. As luzes emitem pulsos de energia em fases diferentes, giram em espiral enquanto apontam para o centro.
    4. Cores variam ao longo do tempo criando um efeito visualmente harmônico e sincronizado.

    Se desejar, posso ajudar a adicionar controladores para sincronizar com música, efeitos de flicker, ou outras lógicas que quiser. Quer que faça?

  5. User

    Python: Traceback (most recent call last): File "\Text.012", line 88, in NameError: name 'direction_to_euler' is not defined

  6. Assistant

    O erro indica que a função direction_to_euler está sendo chamada antes de ser definida. No script que forneci, o direction_to_euler está definido após o loop principal que a chama, causando o NameError.


    Como corrigir?

    Basta mover a definição da função direction_to_euler para cima, antes do loop principal onde ela é usada.


    Script corrigido (apenas as partes relevantes para corrigir o erro):

    import bpy
    import math
    import colorsys
    import mathutils
    
    # --- Função auxiliar para orientar a luz ---
    def direction_to_euler(direction):
        # Converte um vetor direção para Euler (aponta o eixo negativo Z do objeto para a direção)
        vec = mathutils.Vector(direction)
        vec.normalize()
        # A luz padrão aponta para -Z localmente, então rotacionamos para alinhá-la com vec
        rot_quat = vec.to_track_quat('-Z', 'Y')
        return rot_quat.to_euler()
    
    
    # Resto do script abaixo...
    
    # [ ... código de criação das luzes etc. ...]
    
    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
    
        for idx, light in enumerate(lights):
            # Atualiza energia
            e = pulse_energy(frame, idx)
            light.data.energy = e
            light.data.keyframe_insert(data_path="energy", frame=frame)
    
            # Atualiza posição
            pos = spiral_position(frame, idx)
            light.location = pos
            light.keyframe_insert(data_path="location", frame=frame)
    
            # Aponta luz para o centro (opcional)
            direction = (-pos[0], -pos[1], -pos[2])
            light.rotation_euler = direction_to_euler(direction)
            light.keyframe_insert(data_path="rotation_euler", frame=frame)
    
            # Atualiza cor
            c = gradient_color(frame, idx)
            light.data.color = c
            light.data.keyframe_insert(data_path="color", frame=frame)
    

    Mais algumas dicas para evitar erros semelhantes:

    • Sempre defina funções antes de chamá-las no código.
    • Organize o script para que fuja das dependências cíclicas.
    • Se o script crescer, divida em funções claras e definidos no topo.

    Se quiser, posso enviar o script completo corrigido para facilitar, é só pedir!

  7. User

    sim

  8. Assistant

    Claro! Aqui está o script completo corrigido com a função direction_to_euler definida no topo, antes de ser usada. Também organizei o código para facilitar.


    import bpy
    import math
    import colorsys
    import mathutils
    
    # --- Função auxiliar para orientar a luz ---
    def direction_to_euler(direction):
        """Converte um vetor direção para Euler (aponta o eixo -Z local para a direção)."""
        vec = mathutils.Vector(direction)
        if vec.length == 0:
            return mathutils.Euler((0, 0, 0))
        vec.normalize()
        rot_quat = vec.to_track_quat('-Z', 'Y')
        return rot_quat.to_euler()
    
    # --- Configurações da animação ---
    frame_start = 1
    frame_end = 300
    bpy.context.scene.frame_start = frame_start
    bpy.context.scene.frame_end = frame_end
    
    num_lights = 8
    max_radius = 6
    height_amplitude = 3
    
    # Função para limpar luzes existentes
    def clear_lights():
        for obj in bpy.data.objects:
            if obj.type == 'LIGHT':
                bpy.data.objects.remove(obj, do_unlink=True)
    
    clear_lights()
    
    # Cria coleção para as luzes
    col_name = "SyncLights"
    if col_name in bpy.data.collections:
        col = bpy.data.collections[col_name]
    else:
        col = bpy.data.collections.new(col_name)
        bpy.context.scene.collection.children.link(col)
    
    lights = []
    
    # Criação das luzes
    for i in range(num_lights):
        light_data = bpy.data.lights.new(f"PulseLight_{i}", type='SPOT')
        light_data.energy = 800
        light_data.spot_size = math.radians(45)
        light_data.use_shadow = True
        light_data.color = (1, 1, 1)
    
        light_obj = bpy.data.objects.new(f"PulseLight_{i}", light_data)
        col.objects.link(light_obj)
        lights.append(light_obj)
    
    # Funções de controle:
    
    def pulse_energy(frame, idx):
        """Energia da luz com pulso senoidal baseado em frequência/fase."""
        freq = 0.15 + idx * 0.05
        phase = idx * (math.pi / 4)
        base = 400
        amplitude = 600
        val = base + amplitude * max(0, math.sin(freq * frame + phase))
        return val
    
    def spiral_position(frame, idx):
        """Posição em movimento espiral crescendo e oscilação vertical."""
        angle = frame * 0.05 + idx * (2 * math.pi / num_lights)
        radius = (max_radius / frame_end) * frame  # Aumenta radius progressivamente
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = height_amplitude * math.sin(0.1 * frame + idx)
        return (x, y, z)
    
    def gradient_color(frame, idx):
        """Gera cor HSV variando o hue no tempo para cada luz."""
        base_hue = (frame * 0.008 + idx / num_lights) % 1.0
        r, g, b = colorsys.hsv_to_rgb(base_hue, 0.8, 1.0)
        return (r, g, b)
    
    # Animação: aplica keyframes
    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
    
        for idx, light in enumerate(lights):
            # Energia
            e = pulse_energy(frame, idx)
            light.data.energy = e
            light.data.keyframe_insert(data_path="energy", frame=frame)
    
            # Posição
            pos = spiral_position(frame, idx)
            light.location = pos
            light.keyframe_insert(data_path="location", frame=frame)
    
            # Rotação para apontar para o centro
            direction = (-pos[0], -pos[1], -pos[2])
            light.rotation_euler = direction_to_euler(direction)
            light.keyframe_insert(data_path="rotation_euler", frame=frame)
    
            # Cor
            c = gradient_color(frame, idx)
            light.data.color = c
            light.data.keyframe_insert(data_path="color", frame=frame)
    
    print("Animação com pulsos sincronizados e movimento em espiral concluída!")
    

    Como usar:

    1. Copie e cole o script no Editor de Texto do Blender.
    2. Execute o script.
    3. Veja as luzes criando uma bela animação sincronizada com movimento em espiral, pulsos de energia e mudança de cor.

    Se precisar de alguma modificação, efeitos extras ou integração com objetos da cena, me avise!

  9. User

    outro

  10. Assistant

    Claro! Vou criar um terceiro script diferente para uma animação procedural complexa de sincronismo de iluminação em Blender. Desta vez, vamos usar múltiplas luzes que respondem a uma “onda” de brilho que se propaga no espaço com uma combinação de efeitos:

    • Luzes pulsando com sin e cos para criar ondas em 3D.
    • Alteração dinâmica de temperatura da cor (luzes quentes e frias),
    • Luzes se movendo em trajetórias oscilatórias únicas.
    • Uma camada extra de aleatoriedade controlada para criar variações naturais.

    Script 3 - Onda Procedural e Sincronização com Cor Temperatura e Oscilação

    import bpy
    import math
    import random
    import colorsys
    import mathutils
    
    # --- Configurações principais ---
    frame_start = 1
    frame_end = 300
    bpy.context.scene.frame_start = frame_start
    bpy.context.scene.frame_end = frame_end
    
    num_lights = 10
    radius = 7
    
    # Remove todas as luzes da cena
    def clear_lights():
        for obj in bpy.data.objects:
            if obj.type == 'LIGHT':
                bpy.data.objects.remove(obj, do_unlink=True)
    
    clear_lights()
    
    # Cria coleção para as luzes
    col_name = "WaveLights"
    if col_name in bpy.data.collections:
        col = bpy.data.collections[col_name]
    else:
        col = bpy.data.collections.new(col_name)
        bpy.context.scene.collection.children.link(col)
    
    # Cria as luzes
    lights = []
    for i in range(num_lights):
        light_data = bpy.data.lights.new(name=f"WaveLight_{i}", type='AREA')
        light_data.energy = 1000
        light_data.shape = 'SQUARE'
        light_data.size = 1.5
        light_data.use_shadow = True
    
        light_obj = bpy.data.objects.new(name=f"WaveLight_{i}", object_data=light_data)
        col.objects.link(light_obj)
    
        # Posição inicial dispondo em círculo
        angle = 2 * math.pi * (i / num_lights)
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = 2
        light_obj.location = (x, y, z)
    
        lights.append(light_obj)
    
    # Função para converter temperatura de cor (Kelvin) para RGB
    def kelvin_to_rgb(temp):
        # Fonte referência adaptada para valores Kelvin típicos (1000K~40000K)
        temp = temp / 100
        if temp <= 66:
            r = 255
            g = 99.4708025861 * math.log(temp) - 161.1195681661
            b = 0 if temp <= 19 else 138.5177312231 * math.log(temp - 10) - 305.0447927307
        else:
            r = 329.698727446 * ((temp - 60) ** -0.1332047592)
            g = 288.1221695283 * ((temp - 60) ** -0.0755148492)
            b = 255
        r = min(max(r, 0), 255)
        g = min(max(g, 0), 255)
        b = min(max(b, 0), 255)
        return (r / 255, g / 255, b / 255)
    
    # Função ondulatória na posição - cria movimento oscilatório em 3D
    def oscillate_position(frame, idx):
        base_angle = 2 * math.pi * (idx / num_lights)
        speed = 0.05
    
        x = radius * math.cos(base_angle + speed * frame) + 0.5 * math.sin(frame * 0.3 + idx)
        y = radius * math.sin(base_angle + speed * frame) + 0.5 * math.cos(frame * 0.3 + idx)
        z = 2 + math.sin(frame * 0.15 + idx) * 1.8
    
        return (x, y, z)
    
    # Função para causar pulsos de energia com um efeito onda tridimensional
    def wave_energy(frame, idx):
        coord = idx / num_lights * 2 * math.pi
        val = 700 + 700 * max(0, math.sin(coord - 0.1 * frame))  # Pico da onda movendo
        jitter = 50 * math.sin(0.15 * frame + idx)
        return val + jitter
    
    # Função para variar temperatura de cor com oscilações
    def wave_temperature(frame, idx):
        base_kelvin = 2000 + 1500 * math.sin(0.05 * frame + idx)  # 2000K~3500K (quentes)
        flicker = 300 * math.sin(0.2 * frame + idx * 10)
        kelvin = base_kelvin + flicker
        kelvin = max(1000, min(4000, kelvin))
        return kelvin_to_rgb(kelvin)
    
    # Aplica keyframes da animação
    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
    
        for idx, light in enumerate(lights):
            # Atualiza posição oscilatória
            pos = oscillate_position(frame, idx)
            light.location = pos
            light.keyframe_insert(data_path="location", frame=frame)
    
            # Atualiza energia (intensidade)
            energy = wave_energy(frame, idx)
            light.data.energy = energy
            light.data.keyframe_insert(data_path="energy", frame=frame)
    
            # Atualiza cor (temperatura)
            color = wave_temperature(frame, idx)
            light.data.color = color
            light.data.keyframe_insert(data_path="color", frame=frame)
    
    print("Animação procedural de onda de luz criada com sucesso!")
    

    Como usar:

    1. Abra o Blender.
    2. Abra o editor de texto.
    3. Cole o script acima.
    4. Clique em Run Script.
    5. Observe na viewport e no modo rendered a bela animação das luzes oscilando, pulsando e mudando cor sincronizadamente.

    Se desejar, posso ajudar a incluir!

    • Sincronismo com áudio externo
    • Usar luzes emissivas em objetos
    • Controlar parâmetros via drivers e custom properties

    Quer continuar?

  11. User

    outro

  12. Assistant

    Claro! Vou criar um script diferente, com um sistema de iluminação procedural que simula um trânsito de luzes tipo "fogueiras" sincronizadas em ritmo variável, usando luzes POINT com flicker aleatório, mudança suave de cor (de amarelo para vermelho) e movimentos pendulares leves para cada luz.


    Script 4 - Luzes com flicker procedural, cor quente variando e movimento oscilatório

    import bpy
    import math
    import random
    import colorsys
    
    # Configurações
    frame_start = 1
    frame_end = 300
    num_lights = 12
    radius = 8
    max_flicker = 200
    base_energy = 600
    oscillation_amplitude = 0.7
    oscillation_speed = 0.1
    
    bpy.context.scene.frame_start = frame_start
    bpy.context.scene.frame_end = frame_end
    
    # Remove luzes antigas
    def clear_lights():
        for obj in bpy.data.objects:
            if obj.type == 'LIGHT':
                bpy.data.objects.remove(obj, do_unlink=True)
    
    clear_lights()
    
    # Cria coleção para as luzes
    col_name = "Fogueiras"
    if col_name in bpy.data.collections:
        col = bpy.data.collections[col_name]
    else:
        col = bpy.data.collections.new(col_name)
        bpy.context.scene.collection.children.link(col)
    
    lights = []
    
    # Cria as luzes em círculo
    for i in range(num_lights):
        light_data = bpy.data.lights.new(name=f"Fogueira_{i}", type='POINT')
        light_data.energy = base_energy
        light_data.color = (1.0, 0.6, 0.3)  # cor alaranjada inicial
    
        light_obj = bpy.data.objects.new(name=f"Fogueira_{i}", object_data=light_data)
    
        angle = 2 * math.pi * i / num_lights
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = 1.5
    
        light_obj.location = (x, y, z)
        col.objects.link(light_obj)
        lights.append(light_obj)
    
    # Funções auxiliares
    
    def flicker_energy(base, frame, idx):
        random.seed(frame * 100 + idx)
        flicker_val = random.uniform(-max_flicker, max_flicker)
        osc = math.sin(frame * oscillation_speed + idx) * max_flicker * 0.5
        return max(base + flicker_val + osc, 0)
    
    def warm_color_shift(frame, idx):
        # Varie a matiz entre laranja (0.08) e vermelho (0.0) com um leve pulso
        base_hue = 0.04 + 0.04 * math.sin(frame * 0.03 + idx)
        saturation = 1.0
        value = 1.0
        r, g, b = colorsys.hsv_to_rgb(base_hue, saturation, value)
        return (r, g, b)
    
    def oscillate_position(frame, idx, base_pos):
        # Movimento pendular leve na vertical
        x, y, z = base_pos
        z_offset = 0.3 * math.sin(frame * 0.07 + idx)
        return (x, y, z + z_offset)
    
    # Aplica keyframes
    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
    
        for idx, light in enumerate(lights):
            # Energia com flicker
            e = flicker_energy(base_energy, frame, idx)
            light.data.energy = e
            light.data.keyframe_insert(data_path="energy", frame=frame)
    
            # Cor quente variando suavemente
            c = warm_color_shift(frame, idx)
            light.data.color = c
            light.data.keyframe_insert(data_path="color", frame=frame)
    
            # Movimento pendular vertical
            base_pos = light.location
            pos = oscillate_position(frame, idx, (base_pos[0], base_pos[1], 1.5))
            light.location = pos
            light.keyframe_insert(data_path="location", frame=frame)
    
    print("Animação procedural de fogueiras com flicker criada!")
    

    Como funciona

    • Luzes estão distribuídas em um círculo fixo.
    • Cada luz tem um flicker pseudoaleatório de intensidade para simular fogo.
    • A cor varia suavemente entre tons amarelo-alaranjados para vermelho.
    • Luzes oscilam verticalmente para simular chama dançante.

    Se quiser mais efeitos (ex: fumaça, partículas, sincronismo musical, etc), é só pedir!

  13. User

    outro

  14. Assistant

    Claro! Aqui vai um novo script, com uma abordagem diferente e mais complexa para animar luzes em Blender procedimentalmente:


    Script 5 - Sincronismo de Luzes com Partículas e Efeito de “Raio Laser”

    Descrição:
    Este script cria várias luzes tipo SPOT que simulam "raios" laser animados sincronizados, com intensidades pulsantes e cores vibrantes. Além disso, cria um sistema básico de partículas em objetos que "disparam" as luzes, sincronizando a emissão das partículas com a intensidade das luzes para um efeito integrado.


    import bpy
    import math
    import random
    import colorsys
    
    # --- CONFIGURAÇÕES ---
    frame_start = 1
    frame_end = 250
    num_lights = 6
    laser_length = 15
    bpy.context.scene.frame_start = frame_start
    bpy.context.scene.frame_end = frame_end
    
    # Remove luzes e objetos com partículas criados anteriormente
    def cleanup():
        for obj in bpy.data.objects:
            if obj.type == 'LIGHT':
                bpy.data.objects.remove(obj, do_unlink=True)
            if obj.particle_systems:
                bpy.data.objects.remove(obj, do_unlink=True)
    
    cleanup()
    
    # Crie uma coleção para as luzes e objetos
    col_name = "LaserLaser"
    if col_name in bpy.data.collections:
        col = bpy.data.collections[col_name]
    else:
        col = bpy.data.collections.new(col_name)
        bpy.context.scene.collection.children.link(col)
    
    lights = []
    emitters = []
    
    # Função para criar um objeto emissor com sistema de partículas
    def create_emitter(name, location):
        mesh = bpy.data.meshes.new(name)
        emitter = bpy.data.objects.new(name, mesh)
        col.objects.link(emitter)
        emitter.location = location
        
        # Criar sistema de partículas
        psys = emitter.modifiers.new("particles", type='PARTICLE_SYSTEM')
        psettings = bpy.data.particles.new(name + "_settings")
        psys.particle_system.settings = psettings
        
        psettings.count = 50
        psettings.lifetime = 50
        psettings.frame_start = frame_start
        psettings.frame_end = frame_end
        psettings.emit_from = 'VOLUME'
        psettings.physics_type = 'NO'
        psettings.render_type = 'NONE'
        
        return emitter, psys
    
    # Função para criar luz spot laser
    def create_laser_light(name, location, rotation):
        light_data = bpy.data.lights.new(name, type='SPOT')
        light_data.energy = 0
        light_data.color = (1, 0, 0)
        light_data.spot_size = math.radians(6)
        light_data.shadow_soft_size = 0.1
        light_obj = bpy.data.objects.new(name, light_data)
        col.objects.link(light_obj)
        light_obj.location = location
        light_obj.rotation_euler = rotation
        return light_obj
    
    # Cria emissores em círculo e luzes apontadas para o centro
    radius = 8
    for i in range(num_lights):
        angle = (2 * math.pi / num_lights) * i
        
        # Posição do emissor e luz
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = 1.5
        
        emitter, psys = create_emitter(f"Emitter_{i}", (x, y, z))
        emitters.append(emitter)
        
        # Rotação para apontar para centro
        rot_x = math.pi / 2
        rot_z = angle + math.pi
        laser_light = create_laser_light(f"LaserLight_{i}", (x, y, z), (rot_x, 0, rot_z))
        lights.append(laser_light)
    
    # Função para energia pulsante sincronizada em ondas
    def laser_pulse(frame, idx):
        base_energy = 1000
        pulse = max(0, math.sin(frame * 0.15 + idx * math.pi / 3))
        flicker = random.uniform(0.8, 1.2)
        return base_energy * pulse * flicker
    
    # Função para sincronizar emissão de partículas com luz
    def update_particle_emission(psys, energy):
        if energy > 100:
            psys.particle_system.settings.count = 100
            psys.particle_system.settings.frame_start = bpy.context.scene.frame_current
            psys.particle_system.settings.frame_end = bpy.context.scene.frame_current + 3
        else:
            psys.particle_system.settings.count = 0
    
    # Animação
    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
        for idx, light in enumerate(lights):
            energy = laser_pulse(frame, idx)
            light.data.energy = energy
            light.data.keyframe_insert(data_path="energy", frame=frame)
            
            # Cor variando entre vermelho e ciano para dinamismo
            hue = (frame * 0.01 + idx / num_lights) % 1.0
            r, g, b = colorsys.hsv_to_rgb(hue, 1, 1)
            light.data.color = (r, g, b)
            light.data.keyframe_insert(data_path="color", frame=frame)
            
            # Atualizar emissor partículas
            psys = emitters[idx].particle_systems[0]
            update_particle_emission(psys, energy)
    
    print("Animação com lasers procedural criada!")
    

    Como usar:

    • Cole no Editor de Texto do Blender.
    • Rode o script.
    • Veja as luzes tipo laser pulsando em cores vibrantes e partículas “disparando” sincronizadas.

    Quer um script com outra abordagem ou efeitos diferentes? Posso ajudar com cenas de volumetria, sombras dinâmicas ou integração com som!