While the Player function isn't too long right now, it can easily become much larger and become un-manageable. This would particularly be a problem if we make a mistake or want to add a new feature once the Player's function code balloons to several hundred lines of code. So, here's our source code from part 2 of this tutorial series:
from bge import logicNow, then. Let's expand the object's code by making another functions inside of the Player function. How does this work? Well, it's actually quite simple - Python allows us to define a function inside of another function, and so the inside function is only accessible from the 'parent' (outside) function. This just makes the process a bit simpler and more manageable - for example, we can have an Init() function to initialize variables in the object, an Update() function to move that object, and an Animate() function to animate it. With this setup, if we want to add a portion of code, we needn't look in the unrelated portions of code. So, we'll implement this process in our Player's code:
from bge import events
cont = logic.getCurrentController()obj = cont.ownermotion = cont.actuators['Motion']key = logic.keyboard.eventskbleft = key[events.LEFTARROWKEY]kbright = key[events.RIGHTARROWKEY]mx = 0.0my = 0.0if kbleft > 0:mx = -0.1elif kbright > 0:mx = 0.1motion.dLoc = [mx, my, 0.0]cont.activate(motion)
from bge import logicAs you can see, the change in code is very slight. We simple made two new functions, an Init() function for initializing object variables, and an Update() function for moving an object and interacting with that object's code. The Init() function simply checks to see if the object has been initialized - if a variable named init has been created in the object. Because of the check, this Init() function will only initialize any variables and run completely when the object is first created and doesn't have the variable init contained in it. Our Init() function here creates only the init variable to ensure that the object has been initialized.
from bge import events
cont = logic.getCurrentController()obj = cont.ownermotion = cont.actuators['Motion']key = logic.keyboard.eventskbleft = key[events.LEFTARROWKEY]kbright = key[events.RIGHTARROWKEY]def Init():if not 'init' in obj:obj['init'] = 1def Update():mx = 0.0my = 0.0if kbleft > 0:mx = -0.1elif kbright > 0:mx = 0.1motion.dLoc = [mx, my, 0.0]cont.activate(motion)Init()Update()
The Update() function just contains our original code. We then call the Init() and Update() functions at the end to initialize variables (we only create one, the init variable), and move and update our object. As can be seen, it's actually quite simple to implement a very nice containable system that is easy to use. So, this lesson was short, simple, and sweet, as the other lessons should be. Keep havin' fun with the Blender Game Engine as we head into Part 3 of learning how to Use Python in the Blender Game Engine.