Reply To: [ENDED] BC1-1808 – August 2018 Class Homepage – Getting Started with 3D Modeling & Blender 2.8

Forum Archive [ENDED] BC1-1808 – August 2018 Class Homepage – Getting Started with 3D Modeling & Blender 2.8 Reply To: [ENDED] BC1-1808 – August 2018 Class Homepage – Getting Started with 3D Modeling & Blender 2.8

#37823
Zsolt Cseh
Participant

    Just in the mental preparation to the class found an inspiring way to complete the Week 1 exercise to model with primitives – it could be a fun practice to do that through a short Python programming. 

    The idea is maybe a little bit for the advanced users, but you will see it is very simple and fast to run any Python code in Blender, so why not could be inspiring to show also for beginners.

    Actually this code is able to select a random RGB color, switch the engine to Cycles, set the camera in the required distance and angle, then in a loop adding 25 cubes with assigning material to each with that random diffuse color. Look at this in five seconds:

    Somehow finding this as very powerful, let me attach the code concretely, khmm such things could be used for a lot of automation:

    import bpy
    import random
    from math import radians
    def get_random_color():
     r, g, b = [random.random() for i in range(3)]
     return r, g, b

    bpy.context.scene.render.engine = ‘CYCLES’
    obj_camera = bpy.data.objects[“Camera”]
    obj_camera.location = (25.0, -8.0, 17.0)
    obj_camera.rotation_euler = (radians(51), 0.0, radians(53))
    area = next(area for area in bpy.context.screen.areas if area.type == ‘VIEW_3D’)
    area.spaces[0].region_3d.view_perspective = ‘CAMERA’
    for i in range (0, 5):
     for j in range (0, 5):
      x = i*3
      y = j*3
      z = 0
      bpy.ops.mesh.primitive_cube_add(location=(x, y, z))
      cube = bpy.context.object
      mat = bpy.data.materials.new(‘material’)
      mat.diffuse_color = get_random_color()
      mesh = cube.data
      mesh.materials.append(mat)

    It might be useful information yet if someone tries to paste Python code to the inside Python Console in Blender, that the indendation then should be with the space ‘ ‘ characters instead of the tabs. (you can see in the code above that in the for i in range and for j in range sections there are spaces, they are needed in Python). If you would like to reproduce it, after the paste I pressed two Enters for the running