1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Blender の Pythonスクリプト( Blender Python API )を使ったキューブの追加を試す

Last updated at Posted at 2025-03-01

Blender の Pythonスクリプト( Blender Python API )を使ったキューブの追加を試した時のメモ的な記事です。

↓こちらの実装にかんする話になります。

キューブの追加1

まずは、一気に複数のキューブを追加するだけ、という内容を試してみます。

具体的には以下を参考にしつつ、キューブ 3つを指定した座標に置く、というだけのものを作りました。

●【Blender】Pythonスクリプトでオブジェクトの作成や配置を行ってみる|T2
 https://note.com/tomm_4c3/n/n73c323817c66

具体的なコードは以下のとおりです。

import bpy

bpy.ops.mesh.primitive_cube_add(location=(2, 0, 0))
bpy.ops.mesh.primitive_cube_add(location=(5, 0, 0))
bpy.ops.mesh.primitive_cube_add(location=(0, 5, 0))

これで、最初の一歩として以下の処理を実現できました。

キューブの追加2

次は、キューブを一定の時間間隔ごとに追加してみます。

以下を見て、一定時間ごとに処理を行う方法を確認しました。

●Time.sleep() is not working :( - Coding / Python Support - Blender Artists Community
 https://blenderartists.org/t/time-sleep-is-not-working/1410805

●Application Timers (bpy.app.timers) - Blender Python API
 https://docs.blender.org/api/current/bpy.app.timers.html

そして、以下の「1秒ごとにキューブの追加をひたすら繰り返す」というものを作ってみました。キューブ追加の際の xyz の座標は一定の範囲内でランダムな値をとるように実装してみました。

import bpy
import random

def every_1_seconds():
    x = random.uniform(-10, 10)
    y = random.uniform(-10, 10)
    z = random.uniform(-10, 10)

    bpy.ops.mesh.primitive_cube_add(location=(x, y, z))
    
    return 1.0

bpy.app.timers.register(every_1_seconds)

さらに実装を追加してみます。
キューブを追加する際に角度を変化させるというもので、以下のように実装しました。

import bpy
import random
from math import radians

def every_1_seconds():
    x = random.uniform(-10, 10)
    y = random.uniform(-10, 10)
    z = random.uniform(-10, 10)

    bpy.ops.mesh.primitive_cube_add(location=(x, y, z))
    obj = bpy.context.active_object
    obj.rotation_euler = (
        radians(random.uniform(-45, 45)),
        radians(random.uniform(-45, 45)),
        radians(45)
    )

    return 1.0

bpy.app.timers.register(every_1_seconds)

上記を実行した結果、以下の結果が得られました。

Blender での Pythonスクリプト( Blender Python API )の実行

最後に Blender での Pythonスクリプト( Blender Python API )の実行手順をメモします。

手順

GUI上で操作を行う場合での手順メモです。

まずは画面上部の「Scripting」をクリックします。

2025-03-02_00-14-46.jpg

次に画面上部の「+ New」をクリックします。

2025-03-02_00-15-31.jpg

その後にスクリプトを書きます。
スクリプトを書き終わったら、最後に画面上部の再生ボタンを押してスクリプトを実行します。

2025-03-02_00-23-37.jpg

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?