Search This Blog

Sunday, 26 December 2021

BPY SCRIPT TO ADD 50 CUBES AND ANIMATE THEM

In this script we add 50 cubes at random location, set random color to each cube and set key frames to each cube to animate them.

The number of cubes added can be changed by setting the range value in the first for loop.Total number of frames is set in the beginning by setting the value for the variable total_frames. Key frame interval is adjusted by setting the third variable in the range setting of the second for loop.Here it is set to 10. The diffuse color setting has four values for Red, Green, Blue and Alpha.

import bpy
from math import sin, pi
from random import randint

total_frames=100

# clear meshes in the scene
for obj in bpy.data.objects:
    if obj.type == 'MESH':
        bpy.data.objects.remove(obj)

#CREATE 10 CUBES        
for i in range (50):
    x=randint(-10,10)
    y=randint(-10,10)
    z=randint(-10,10)    
    bpy.ops.mesh.primitive_cube_add( location=(x,y,z))
    cube=bpy.context.object
    # TO ADD NEW MATERIAL TO EACH CUBE
    matl=bpy.data.materials.new("mat_clr")
    matl.diffuse_color = (x*0.6,y*0.3,z*0.1,1)
    mesh=cube.data
    mesh.materials.clear()
    mesh.materials.append(matl)
    
    # SET KEYFRAMES FOR EACH CUBE
    for frame in range(0, total_frames,10):
        bpy.context.scene.frame_set(frame)
        x=randint(-10,10)
        y=randint(-10,10)
        z=randint(-10,10)

        cube.location=(x,y,z)
        cube.keyframe_insert(data_path='location')

 

A link to the rendered video file is given below:

https://drive.google.com/file/d/1ZSFBqbky9fEUKng0ZanPFgLFlcWgkLO1/view?usp=sharing

 

No comments:

ROUND EDGES- BEVEL TOOL

Blender version 3.6 To make any edge to be rounded smoothly, we can use the bevel tool in Edit Mode. Look at the cube in Image 1 where all t...