I am trying to create a class that will manage the x position of an object. So I created a script that runs in the frame changed event of an object.
I want to do this with a class. However, it seems that the namespace of the frame change event falls out of scope at the end of the event. This means that my class goes out of scope every frame.
I want a way to have a class that persists between framechange events. Does any one know how to do this.
Here is my code so far:
import Blender as B # Create a class to manage the spring math. class springMotion: # Alter these constants for different spring motion. inertia = 0.85 k = 0.15 def __init__ (self, beginPos, targetPos): #self.id = id self.isMoving = 0 self.motion = 0 self.beginPosition = beginPos self.targetPosition = targetPos self.position = beginPos def update (self): diff = (-1 * self.position) + self.targetPosition self.motion = (self.motion * self.inertia) + (diff * self.k) if abs(self.motion) < 0.1 and abs(diff) < 0.1: self.position = self.targetPosition self.isMoving = 0 else: self.isMoving = 1 self.position = self.position + self.motion #Our program begins here. obj = B.Object.Get('Cube') #frame = B.Get('curframe') try: # Try to update our class. print ("trying to see if our class exists") mySpring.update() obj.LocX = mySpring.position print ("Updated position") except: # We end up here if our class has not been created. mySpring = springMotion(0,100) mySpring.update() obj.LocX = mySpring.position print ("Created class:" + str(obj.LocX))
If you attach this script to the default cube object on Blender start up you will see that it always runs in the exception case. This is where the code should run on first run. There is no class so a class is created. Then, the intention, is to update the x position on every frame with the new position. This never happens because when the frame change event exits, the class falls out of scope. Then when the frame change happens again, there is a new namespace and there is no “mySpring” class, so we end up in the except case again.
I guess I need a way for a class to be global.