Last active
April 18, 2022 17:31
-
-
Save NanoDano/0c0fcf927c738f063ff888106ece2b99 to your computer and use it in GitHub Desktop.
Blender3D script to generate and animate bouncing cubes
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
import bpy | |
import random | |
# Reference: https://www.youtube.com/watch?v=r8hqLh_HE08 | |
# After running the script, go to the Animation tab and hit SPACE to run the animation | |
def delete_all_cubes(): | |
# Select all cubes by name | |
for o in bpy.context.scene.objects: | |
#if o.type == 'MESH': | |
if o.name.startswith('Cube'): | |
o.select_set(True) | |
else: | |
o.select_set(False) | |
# Call the delete operator only once | |
bpy.ops.object.delete() | |
def generate_cubes(): | |
SPACING=2.5 | |
for x in range(5): | |
for y in range(5): | |
bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', | |
location=(x * (SPACING), y * (SPACING), random.random() * 2), scale=(1, 1, 1)) | |
item = bpy.context.object # Get last object made | |
# Set keyframes to animate the cubes | |
original_z = item.location[2] | |
item.keyframe_insert(data_path="location", frame=1) | |
item.location = (item.location[0], item.location[1], -1) | |
item.keyframe_insert(data_path="location", frame=12) | |
item.location = (item.location[0], item.location[1], original_z) | |
item.keyframe_insert(data_path="location", frame=24) | |
# Pick one of 2 random textures (Go make the textures yourself) | |
if random.random() < 0.2: | |
item.data.materials.append(bpy.data.materials['Material.002']) | |
else: | |
item.data.materials.append(bpy.data.materials['Material.001']) | |
# Main | |
delete_all_cubes() | |
generate_cubes() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment