Graphics Reference
In-Depth Information
Open a text editor and add a new text file called portal.py . To the Sphere object, add a Collision sensor
andaPythoncontroller,asshownin Figure16-6 . TheCollisionsensoriscalled hitportal ,anditisactivated
on collision with objects with property port . The Python controller calls the portal.py script.
Figure 16-6 Logic for the sphere
Code for the Teleportation Machine
Now that the objects and logic bricks are in place, you can turn your attention to the code. The code begins
by assigning the GameLogic module to a shorthand variable, as in the previous case. Then, the controller and
owner are retrieved and assigned to variables as shown here:
from bge import logic as GL
cont = GL.getCurrentController()
scene = GL.getCurrentScene()
own = cont.owner
Aside from the owner object, which is the Sphere, it is also necessary to retrieve the other objects from the
scene. The GL.getCurrentScene() method will return the current scene. The scene, in turn, has a prop-
erty objects that contains a collection of the objects in the scene in the form of a Python dictionary.
The objects property can be accessed by the 3D object names as keys; use print ( scene.objects ) if
you want to see this list in the System Console. The following code assigns the actual 3D Torus objects to ap-
propriately named variables:
torus1 = scene.objects["Torus1"]
torus2 = scene.objects["Torus2"]
torus3 = scene.objects["Torus3"]
torus4 = scene.objects["Torus4"]
The next lines of the code retrieve the Collision sensor from the controller and then query the Collision
sensor for the object that was hit. As always, the dir() command can be relied on to find out the name of the
appropriatemethods.Calling dir() onaCollisionsensorobjectwilldisplayalistofmethodsthatincludesthe
property hitObject . This is the property to use to retrieve the object that was collided with. In the following
code, the object is passed to a variable called hit :
col = cont.sensors["hitportal"]
hit = col.hitObject
To make sure that the property calls are well defined in the subsequent code, add an if clause to ensure
that hit has an actual value. What happens next depends on the port property value of the hit object. If the
 
 
Search WWH ::




Custom Search