BlenderをPythonで操作したメモ20240321

BlenderにあるオブジェクトをPythonを使って動かしてみました。

オブジェクトが中心にある状態から始めてみます。

以下のPythonスクリプトを実行するとオブジェクトを動かすことができました。

import bpy

obj = bpy.data.objects["Cube"]  # Replace with your object's name

# Animation parameters
start_frame = 1
end_frame = 60  # How long the movement takes
distance = 5  # Total distance to move

# Calculate the step distance per frame
total_frames = end_frame - start_frame
step_distance = distance / total_frames

# Set the initial position and keyframe
obj.location.x = 0
obj.keyframe_insert(data_path="location", frame=start_frame)

# Incrementally move and keyframe
for f in range(start_frame + 1, end_frame + 1):
    obj.location.x += step_distance
    obj.keyframe_insert(data_path="location", frame=f)

オブジェクトを元の位置に戻す際は、オブジェクトを選択した状態でGキーを押すことでオブジェクトを画面上で操作できるようにできました。

また、以下のPythonスクリプトでもオブジェクトを中央の位置に戻すことができました。

import bpy

obj = bpy.data.objects["Cube"]  # Replace with your object's name
obj.location = (0, 0, 0)