Key events

Heya,
I can’t get key events working :confused: :
with this code

self.accept('space', hello)

I get “global name self is not defined”
and without “self” it say me that accept is unknown.

structure of the code :

def createWorld():
    self.accept('space', hello)
    run()    

There is no class

How to get this working?

THanks a lot and sorry for my poor english :blush:
[/code]

Welcome to the world of object oriented programming :slight_smile:

“self” has only a meaning inside a class. Inside a class “self” is a reference to the class instance itself (hence “self”). Similar to “this” in C++.

To get familiar with classes in Python I suggest reading chapter 9 of the tutorial that comes with Python.

Now for the “accept”. Accept is a method of the class “DirectObject”, one of the many classes Panda3D offers. To use it you must have either an instance of the class DirectObject, or an instance of a class derived from DirectObject.

This would be deriving (your class inherits all the methods of class DirectObject, and among them “accept”):

import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject

class World( DirectObject ):
    def __init__( self ):
        self.accept( 'space', self.hello )
    def hello( self ):
        print 'hello'

o = World( )
run( )

And this using an instance of DirectObject directly:

import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject

def hello( ):
    print 'hello'

o = DirectObject( )
o.accept( 'space', hello )

run( )

Both examples should work and print “hello” to the console each time you press space.
enn0x

Thanks a lot enn0x, it works :slight_smile:
I tried with directObject.accept but not this issue