Classes, sdfgeoff style:
By now you have probably learned about functions, and how you can use them to hold operations. Well, a class is a way to store functions.
In a script there is often more than one thing happening, so you might read a file, then get a bit of information from it, interpret that information, and finally act on it.
Classes allow you to divide up your script into the different sections.
So you can have a class for your file management functions, and a class for your AI functions, and so-on/so-forth until you get tired.
To use a class you have to create it (obviously), and to do so you use the class statement. For example this will create a class called AI:
class AI:
And then you put your functions in it, like so:
class AI:
def getAngleBetween(source, target, axis):
'''Get's the angle between source and target'''
dis, gvec, lvec = source.getVectTo(target)
angle = lvec.angle(mathutils.Vector(axis),90)
angleDeg = math.degrees(angle)
return angleDeg
def hasDirectSightOn(source, target):
'''See's if there's a direct line between the source and target'''
hitObject = source.rayCastTo(target)
return id(hitObject) == id(target)
def seeking(obj, cont, LR, UD):
'''Activates the actuator 'seek' and deactivates the tracking'''
seek = cont.actuators["seek"]
cont.activate(seek)
cont.deactivate(LR)
cont.deactivate(UD)
And so on.
So then you want to use one of these functions, so you have to call it.
You do it in the same way as you do a module, so to call getAngleBetween you use:
AI.getAngleBetween(obj, enemy, [0,0,1])
From anywhere in the script.
Say that for part of the function “getAngleBetween” we called the function “seeking” We can refer to it by using AI.seeking, like you would from out of the class, but the preferred way is to use a thing called “self.”
When you write your function, have as the first parameter “self” You do not need to put anything in that when you call it.
So getAngleBetween becomes:
def getAngleBetween(self, source, target, axis):
'''Get's the angle between source and target'''
dis, gvec, lvec = source.getVectTo(target)
angle = lvec.angle(mathutils.Vector(axis),90)
angleDeg = math.degrees(angle)
return angleDeg
Then to refer to another function in the same class you use:
self.seeking
This is the limit of my knowledge of classes at the moment, I only learned about them about 2 months ago, so I’m probably missing heaps.
Good Luck
sdfgeoff out