-
-
Save wakarase/4c5b2554b832f7cd75b2922c50f5d3fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# BlenderユーザーのためのPython入門 | |
# 第22節 ランダムな色の複数の球を並べる | |
import bpy | |
import random | |
def delete_all(): | |
"""既存のメッシュとマテリアルを削除します。""" | |
for mesh in bpy.data.meshes: | |
assert isinstance(mesh, bpy.types.Mesh) | |
bpy.data.meshes.remove(mesh) | |
for material in bpy.data.materials: | |
assert isinstance(material, bpy.types.Material) | |
bpy.data.materials.remove(material) | |
def make_material(name): | |
"""ランダムな色のマテリアルを作成します。""" | |
material = bpy.data.materials.new(name) | |
assert isinstance(material, bpy.types.Material) | |
r = random.random() | |
g = random.random() | |
b = random.random() | |
color = (r, g, b, 1.0) | |
material.diffuse_color = color | |
material.use_nodes = True | |
principled_bsdf = material.node_tree.nodes['Principled BSDF'] | |
assert isinstance(principled_bsdf, bpy.types.ShaderNodeBsdfPrincipled) | |
principled_bsdf.inputs['Base Color'].default_value = color | |
principled_bsdf.inputs['Metallic' ].default_value = 1.0 | |
principled_bsdf.inputs['Roughness' ].default_value = 0.0 | |
return material | |
def make_sphere(x, y, z): | |
"""座標(x, y, z)に球を作成します。""" | |
bpy.ops.mesh.primitive_uv_sphere_add(location=(x, y, z)) | |
bpy.ops.object.shade_smooth() | |
object = bpy.context.active_object | |
assert isinstance(object, bpy.types.Object) | |
material = make_material('Color' + str(x) + str(y)) | |
# オブジェクトにマテリアルスロットを用意してマテリアルを割り当てます。 | |
if random.random() > 0.5: # どちらでもいいです。 | |
mesh = object.data | |
assert isinstance(mesh, bpy.types.Mesh) | |
mesh.materials.append(material) | |
else: | |
bpy.ops.object.material_slot_add() | |
for slot in object.material_slots: | |
assert isinstance(slot, bpy.types.MaterialSlot) | |
slot.material = material | |
def make_spheres(num_x, num_y): | |
"""複数の球らを作成します。""" | |
for x in range(num_x): | |
for y in range(num_y): | |
# 例えばnum_xが7なら-6, -4, -2, 0, 2, 4, 6とします。 | |
make_sphere(x * 2 - (num_x - 1), y * 2 - (num_y - 1), 0) | |
if __name__ == '__main__': | |
delete_all() | |
make_spheres(7, 7) # 7x7個の球を作ります。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment