Triggering Events When Agents Collide
<< previous | Chapter 7. Interactions Between Agents | next >>

## Triggering Events When Agents Collide

It is frequently desirable to have agents perform some sort of interaction when they collide. The agents might exchange information, fight or reproduce, for example. In order to specify what happens when a collision occurs, use the method handle-collisions found in Real.tz. This method expects a `string` method name, which is the method that will be invoked when the collision occurs, and a `string` type, which specifies the class name to set up the handler for.

The handler method must accept a single argument, of type `object`. When a collision occurs, the method is called with the object that was encountered. In the following code excerpt, for example, an agent defines a method called "setup-collision-handler" to setup a collision handler for a (fictional) class called "Food". When the agent collides with a piece of food, the method "eat" will be called, and the argument passed in is the piece of food with which the agent has collided:

    + to setup-collision-handler:
            self handle-collisions with-type "Food" with-method "eat".

    + to eat foodObject (object):
            print "I just ate $foodObject.  It was yummy.".
            free foodObject.

If two agents collide, and both have collision handlers setup, then the collision callbacks are not guaranteed to be executed in any particular order. It is sometimes desirable for both objects to execute their callbacks, while in other cases, only one agent should execute the callback. If the callback is expected to trigger a one-time interaction (like a fight) for example, then you don't want to allow the callback to be executed for both agents. In this case, make your collision handler return a positive number. If the first callback method returns a positive number, then the second callback will not be executed. If the callback returns zero, or doesn't return a value at all, both callbacks will be executed.

<< previous | Up | next >>
Chapter 7. Interactions Between Agents | Table of Contents | Finding Neighboring Objects