Game Development Reference
In-Depth Information
Figure 5-41. A few of the “Messages” that are used as functions
Different types of games will use different callbacks. A classic adventure game will use
OnMouseDown() to track the user picking various items in the scene. First-person shooters, will make
heavy use of OnCollisionEnter() , where physics control a lot of the action. Let's do a few tests to
see how they work.
Using Collisions to Call Functions
OnCollisionEnter() and its close relative OnTriggerEnter() are a mainstay of most 3D games. The
first allows you to set off events like explosions, audio, and special effects when objects collide.
The second is a bit more subtle, letting you trigger events or change states when the object passes
through the (usually invisible) object.
The trickiest part about using either function is that the triggering object, at least, must contain
a Rigidbody component. This may not sound like an issue—after all, projectiles usually contain
Rigidbody components. When they hit something, a lot of events can be triggered. The problem
comes when trying to use, say, the First Person Controller to trigger something. The First Person
Controller doesn't contain a true Rigidbody component, as several of its physics-type properties
are rolled into its Character Controller component. The newer First Person Character prefab (not
yet available as a standard asset) will help to solve this issue, as it contains an actual Rigidbody
component. The important thing to remember is that at least one of the objects must contain a
Rigidbody component.
The bench will serve nicely for some preliminary tests, so let's begin.
1.
Right-click over the Test Scripts folder in the Project view and, from Create,
select C# Script.
2.
Name it ColliderTests .
3.
Double-click on it to open it in the script editor.
Below the Update function, add the following:
4.
void OnCollisionEnter () {
print ("Ouch!");
}
 
Search WWH ::




Custom Search