gpt-4-0314· openai
Suzhen/CodeChat
Write python script for blender that animates 3d spirals
- User
Write python script for blender that animates 3d spirals
- Assistant
Write python script for blender that animates 3d spirals
To create an animated 3D spiral in Blender using Python, you can follow these steps:
import bpy
import math
def create_spiral(name, num_points, scale_factor, radius, angle_increment):
# Create new curve object
curve_data = bpy.data.curves.new(name, type='CURVE')
curve_data.dimensions = '3D'
# Create spline and set it to Bezier Curve
spline = curve_data.splines.new(type='BEZIER')
spline.bezier_points.add(num_points - 1)
# Set the control points' coordinates
for idx, point in enumerate(spline.bezier_points):
angle = angle_increment * idx
x = radius * math.cos(angle)
y = radius * math.sin(angle)
z = idx * scale_factor
point.co = (x, y, z)
point.handle_left_type = 'AUTO'
point.handle_right_type = 'AUTO'
# Create curve object and link it to the scene
curve_obj = bpy.data.objects.new(name, curve_data)
bpy.context.collection.objects.link(curve_obj)
return curve_obj
def animate_spiral(spiral_obj, start_frame, end_frame, rotation_axis, rotation_angle):
# Set initial rotation
spiral_obj.rotation_euler[rotation_axis] = 0
spiral_obj.keyframe_insert(data_path='rotation_euler', frame=start_frame, index=rotation_axis)
# Set final rotation
spiral_obj.rotation_euler[rotation_axis] = rotation_angle
spiral_obj.keyframe_insert(data_path='rotation_euler', frame=end_frame, index=rotation_axis)
# Clear pre-existing mesh objects
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.object.select_by_type(type='CURVE')
bpy.ops.object.delete()
# Create spiral curve and animate it
spiral_name = 'Spiral'
num_points = 100
scale_factor = 0.2
radius = 2
angle_increment = math.radians(15)
spiral_obj = create_spiral(spiral_name, num_points, scale_factor, radius, angle_increment)
start_frame = 1
end_frame = 250
rotation_axis = 2 # 0 for X, 1 for Y, 2 for Z
rotation_angle = math.radians(360)
animate_spiral(spiral_obj, start_frame, end_frame, rotation_axis, rotation_angle)
Remember that this script creates and animates a spiral using Bezier curves, not a mesh. If you want a mesh, you can convert the curve to a mesh using 'bpy.ops.object.convert(target='MESH')' after selecting the curve object (spiral_obj in this case).