[Blender][スクリプト]シーン内の全オブジェクトの移動

をしたい、という事が良くあるのですが、キーが打ってあったり階層構造があったりコンストレインがあったりするとうまくいきません。
なのでchatGPTにスクリプトを書いてもらいました。

色んな状況があるので、段階的にスクリプトにしてもらいました。


1.シーン内全選択。この時、階層構造を持っているものはルートのみ選択。階層構造を持たないものはそのまま選択する。

import bpy

def select_root_objects():
    # 現在の選択をクリア
    bpy.ops.object.select_all(action='DESELECT')
    
    # すべてのオブジェクトをチェック
    for obj in bpy.context.scene.objects:
        # 親がない場合はそのまま選択
        if obj.parent is None:
            obj.select_set(True)
        # 親がある場合、ルートまで遡ってルートオブジェクトを選択
        else:
            root = obj
            while root.parent is not None:
                root = root.parent
            root.select_set(True)

# ルートオブジェクトを選択
select_root_objects()


2.選択されたオブジェクトの内、コンストレインで制御されたものを除外する。

import bpy

def deselect_constrained_objects():
    # 現在の選択を取得
    selected_objects = bpy.context.selected_objects
    
    # コンストレインされたオブジェクトをリストに追加
    constrained_objects = [obj for obj in selected_objects if obj.constraints]

    # コンストレインされたオブジェクトを選択から外す
    for obj in constrained_objects:
        obj.select_set(False)

    # 除外後の選択状態を確認するために選択されていないオブジェクトを表示
    remaining_objects = [obj.name for obj in bpy.context.selected_objects]
    print(f"Remaining selected objects: {remaining_objects}")

# コンストレインされたオブジェクトを除外
deselect_constrained_objects()


3.選択中のオブジェクトを移動する。この時、キーが打たれたものはFカーブごとオフセットする。(スクリプト内で数値を設定)

import bpy

def move_selected_objects(move_x, move_y, move_z):
    selected_objects = bpy.context.selected_objects
    
    for obj in selected_objects:
        # トランスフォームを移動
        obj.location.x += move_x
        obj.location.y += move_y
        obj.location.z += move_z
        
        # キーフレームがある場合も移動
        if obj.animation_data and obj.animation_data.action:
            for fcurve in obj.animation_data.action.fcurves:
                if fcurve.data_path.endswith("location"):
                    for keyframe in fcurve.keyframe_points:
                        if fcurve.array_index == 0:
                            keyframe.co[1] += move_x
                        elif fcurve.array_index == 1:
                            keyframe.co[1] += move_y
                        elif fcurve.array_index == 2:
                            keyframe.co[1] += move_z

# 移動量を設定
move_x = 5.0
move_y = 5.0
move_z = 5.0

# 選択中のオブジェクトを移動
move_selected_objects(move_x, move_y, move_z)

この記事が気に入ったらサポートをしてみませんか?