Python: How to Automate Circle Animation

lowrescarnival

Alright, this is the last of the circle functions. That’s a lie. The sine/cosine thing took me so long to wrap my head around, I’ll be using these functions in every animated scene I make from this point forward.

After making a function to automate making objects into a circle, I figured automating an object into a circle would be nice and simple, and for once, it was. (Mostly because benjmorgan posted the code in comments). The part that took me a while was shoving in a few more variables into the right spots to make multiple objects go in the same circle. Like you might need if you’re modeling a Ferris wheel.

Here’s a breakdown:

Somehow in adding notes, I made this more confusing

Nope, still confused.

Why are both a and b being moved up by 6.283/len(bpy.context.selected_objects)?

Since I want the objects evenly placed evenly within the circle, at least one variable needs to be the number of objects divided by 6.283. That’s because the sine and cosine functions both return points based on the number of radians, and MathIsFun.com told me there are 6.283 radians in a circle.

And len(bpy.context.selected_objects) will return the number of selected objects.

If you slow down the while loop, it’s easier to see how the a variable ties into the x and y coordinates. This one is set for a scene with 10 selected objects.

codegif

Since the while loop is inside the for loop, it will add keyframes at 0, 10, 20, 30, 40, 50, 60, 70, 80 and 90 before moving on to the next object.

But if you run the same while loop for every object, all your objects will have the same coordinates at the same keyframes. That’s no good.

UNLESS you plug another variable equal to the starting value of a to offset the next object’s starting point in the circle. Like so:

How pretty

What’s beautiful about this is if you’re modeling a carnival ride, you can duplicate the passenger car thirty times and run the script once to animate it.

Here’s the copy/paste version:

import bpy
import math

def animcircle(frames):
i=0
a=0
b=0
for obj in bpy.context.selected_objects:
i=0
a=a+b
while i < frames:
obj.location.x=math.cos(a)
obj.location.y=math.sin(a)
obj.keyframe_insert(data_path="location",frame=i)
a+=6.283/(len(bpy.context.selected_objects))
i+=10
b+=6.283/(len(bpy.context.selected_objects))
a=0

animcircle(200)

 

 

2 Replies to “Python: How to Automate Circle Animation”

Leave a comment