スキップしてメイン コンテンツに移動

21個の球体を1単位毎に配置し、中央の球体を赤色に塗るPythonコード

21個の球体を1単位毎に配置し、中央の球体を赤色に塗るPythonコード



import bpy
from mathutils import Vector

# 配置する球体の個数
n_spheres = 21

# 球体を配置する半径
radius = 1

# 球体の半径
sphere_radius = 0.1

# 中央の球体を赤色にするフラグ
red_sphere = True

# 球体を配置する
for i in range(n_spheres):
    # 球体の中心位置を計算
    x = (i - (n_spheres - 1) / 2) * radius
    loc = Vector((x, 0, 0))
    
    # 球体を作成
    bpy.ops.mesh.primitive_uv_sphere_add(radius=sphere_radius, location=loc)
    obj = bpy.context.active_object
    
    # 中央の球体を赤色にする
    if red_sphere and i == (n_spheres - 1) // 2:
        mat = bpy.data.materials.new(name="Red")
        mat.diffuse_color = (1, 0, 0, 1)
        obj.data.materials.append(mat)
    else:
        mat = bpy.data.materials.new(name="Gray")
        mat.diffuse_color = (0.5, 0.5, 0.5, 1)
        obj.data.materials.append(mat)