隅歩つ

書いて理解を深める

Blender PythonAPIのsin,cosで螺旋を作る

BlenderPython APIを勉強中です。

今回は、sin、cosの使い方を調べてみました。

コードの説明

まず、sin、cosを使うためにmathモジュールをインポートします。

sin、cosを使う場合にmathモジュールは必須です。

import bpy
import math

書き方は、「math.sin(x)」「math.cos(x)」のように書きます。

また、ラジアンに変換する必要があります。

ラジアンは、「math.radians(x)」と書きます。

x = math.cos(math.radians(i*10))*10
y = math.sin(math.radians(i*10))*10

ちなみに、角度に変換する場合は、「math.degrees(x)」です。

コード全体

コード全体は以下となります。

球体の数は、300個です。

import bpy
import math

NUM = 300
sca = 0.5


def all_delete():
    for item in bpy.data.meshes:
        bpy.data.meshes.remove(item)


def make_cube(x, y, z):
    loc = (x, y, z)
    sphere = bpy.ops.mesh.primitive_uv_sphere_add(
        scale=(sca, sca, sca), location=loc)


def make_cubes(num):
    for i in range(num):
        x = math.cos(math.radians(i*10))*10
        y = math.sin(math.radians(i*10))*10
        z = i/5
        make_cube(x, y, z)


if __name__ == '__main__':
    all_delete()
    make_cubes(NUM)

ちょっとずつ書き方がわかってきて楽しくなってきました。

yuuuha.hatenablog.com

BlenderユーザーのためのPython入門

BlenderユーザーのためのPython入門

  • 作者:大西武
  • シーアンドアール研究所
Amazon