Created
June 30, 2018 16:36
-
-
Save gifguide2code/45e059fb4ef1d9bcaa164c259aae7e67 to your computer and use it in GitHub Desktop.
A Python function to create confetti in Blender, more specifically it'll create 100 small planes, assign those a new texture, and randomize their location. The confetti function takes three parameters--the first is the name of the material to be assigned, the next three are the RGB values for that material. The code below will generate yellow, g…
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 | |
def confetti(MatCol,r,g,b): | |
bpy.ops.mesh.primitive_plane_add() | |
bpy.ops.transform.resize(value=(.1,.1,.1)) | |
#Resize to fit the scene | |
bpy.data.objects['Plane'].name = MatCol | |
#Rename the planes as the 1st paramater above | |
mat_name = MatCol | |
mat = bpy.data.materials.new(mat_name) | |
bpy.data.materials[mat_name].use_nodes = True | |
bpy.data.materials[mat_name].node_tree.nodes.new(type='ShaderNodeEmission') | |
inp = bpy.data.materials[mat_name].node_tree.nodes['Material Output'].inputs['Surface'] | |
outp = bpy.data.materials[mat_name].node_tree.nodes['Emission'].outputs['Emission'] | |
bpy.data.materials[mat_name].node_tree.links.new(inp,outp) | |
bpy.data.materials[mat_name].node_tree.nodes['Emission'].inputs[0].default_value = (r,g,b,1) | |
bpy.data.objects[MatCol].active_material = bpy.data.materials[mat_name] | |
#Run a loop 100 times | |
for index in range(100): | |
bpy.ops.object.select_all(action='DESELECT') | |
#If you don't deslect the other objects, the results are real weird | |
bpy.data.objects[MatCol].select = True | |
x=random.uniform(-10,10) | |
y=random.uniform(-10,10) | |
z=random.uniform(-10,10) | |
#Randomize some variables to plug into the location parameter | |
bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False,"mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(x,y,z)}) | |
#Duplicate the object and keep it unlinked | |
confetti("YellowMat", 1, 1, 0) | |
confetti("GreenMat", 0, 1, 0) | |
confetti("RedMat", 1, 0, 0) | |
confetti("BlueMat", 0, 0, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you might want to change
bpy.data.objects[MatCol].select = True to bpy.data.objects[MatCol].select_set(True)
for 2.8 and up.
I ran into an error and found this on the subject:
https://blender.stackexchange.com/questions/141330/problem-with-bpy-context-selected-objects
very helpful script for getting familiar with blenders data structures!! Thanks for sharing!!!