Initialization = set a value.
“outside a function” sounds like you need data that persists the end of the script. In that case local variables will not be sufficient as they will die when the script ends.
I suggest to use a property. A property lives in the scope of the 3D object. This makes a lot of sense as you do not need this data when the 3d character is not present anymore.
When I read it right you have two events:
You want to know how long the in air state lasts.
So I suggest you store the time when the character enters the in-air state (begin time).
When the character leaves the in-air state you measure the time again (end time).
The difference between both times is the time in air (air time).
There are many ways to implement that - even with logic bricks it is no big deal (there is a timer property).
When using Python you need to be aware these are two different operation at different times. You will need to store at least the begin time in a way that it survives till it is need for the air time calculation.
beginInAir.py
import bge
from datetime import datetime
if all(sensor.positive for sensor in bge.logic.getCurrentController().sensors):
beginTime = datetime.now()
character = bge.logic.getCurrentController().owner
character["beginTime"] = beginTime
print("begin time", beginTime)
endInAir.py
import bge
from datetime import datetime
if all(sensor.positive for sensor in bge.logic.getCurrentController().sensors):
endTime = datetime.now()
character = bge.logic.getCurrentController().owner
beginTime = character["beginTime"]
airTime = endTime - beginTime
print("end time", endTime)
print("air time", airTime)
You might even want to combine them into one script. Be aware this increases complexity quite a lot. This can be useful when you have the same sensors measuring both events positive and not positive (e.g. a ray or collision sensor).
import bge
from datetime import datetime
if all(sensor.positive for sensor in bge.logic.getCurrentController().sensors):
beginTime = datetime.now()
character = bge.logic.getCurrentController().owner
character["beginTime"] = beginTime
print("begin time", beginTime)
else:
endTime = datetime.now()
character = bge.logic.getCurrentController().owner
beginTime = character["beginTime"]
airTime = endTime - beginTime
print("end time", endTime)
print("air time", airTime)
As the data is hold at the 3D object, you can use this code on any number of objects. Do not use it on the same object twice!
Requirements:
- the object does not start in-air
- the beginInAir code is executed first.
Otherwise you will get an error as the begin-time is not known.