Collisions and sensors¶
In addition to reacting to events, tokens can also use sensors to check whether other tokens are in the same place, for example.
Detect an object¶
token can track down another
token in the same location as follows:
What happens here?¶
on_sensing_tokenis called when the token detects another object at the same location.
otheris a reference to the found object, so you can directly access attributes and methods of this object (e.g. with
Compare with found object¶
Often an action should only be executed if a certain object is found.
This goes like this, for example:
1player 2 = miniworldmaker.token() 2#... email@example.com 4def on_sensing_token(self, other): 5 global player2 6 if other == player2: 7 print("I found you, player2!")
The comparison in line 6 checks if the object is the same object as
- … note::
excursion: global variables: Normally variables are only known within a method, to prevent e.g, to avoid side effects when accessing the same variable in different places.
The approach with which variables from other program parts are accessed here is simple and intuitive. But later one will try to avoid this.
Check boundaries of the playing field¶
You can also check if a piece is at the borders of the playing field (or beyond):
Is the piece not on the board?.
Is the character on the boundaries of the board?.
If a character is at position (0,0) the following is printed: Borders are here! [‘right’, ‘top’]
My collisions are not detected, what can I do?
First test if the method is called at all, e.g. with:
@player.register def on_sensing_token(self, token): print(token) ...
More information. See Key Concepts: Sensors.
The objects can be tracked in different ways. This can be set via the
collision_typeproperty of the object being tracked, e.g. “mask” for a pixel-exact comparison or ‘rect’ if only the enclosing rectangles are compared.