我正在使用 OpenGL 在 python 中构建一个简单的游戏。
我通过类构建逻辑,类生成信息并将其传递给 OpenGL。
不幸的是,OpenGL正在使用回调,我不知道如何在此过程中使用我的类方法。
class Drawer(object):
level = 0
def main_draw():
...
glutInit()
glutTimerFunc(interval, update, 0)
glutDisplayFunc(self.draw) #<----- here's my trouble
glutIdleFunc(self.draw) #<----- here's my trouble
...
def draw():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
refresh2d_custom(width, height, field_width, field_height)
#TODO
draw_walls()
glutSwapBuffers()
我认为静态方法不起作用,因为我的类将有多个实例。
如果我直接使用函数(这似乎是迄今为止最简单的解决方案),我将如何将实例传递给特定文件?
#draw.py
#instance that has been pass to this file. It is not instanciated in draw.py
#level would be global in this file
level = MyGameInstance.level
最佳答案
将 self
参数添加到对象的函数中,这样您就可以在对象被回调时访问该对象。无论如何,都需要 self
参数来使其运行,因为这是一种非静态方法(因此至少需要一个参数)。
关于python - 将类方法作为回调传递(面向对象编程 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31255351/