Game Development Reference
In-Depth Information
Collisions and Responses
Let's move further with the Powerup_Dollar class to handle collision events. For Unity game objects
with Trigger components, the OnTriggerEnter event is fired for the object when either a RigidBody
object or another collider , such as the Player character, moves inside the trigger area (or volume).
The extents of the trigger are defined by the BoxCollider. There is also a partner OnTriggerExit event,
which is invoked when the collider leaves the trigger volume. However, in this topic, we'll only need to
deal with OnTriggerEnter . Listing 4-12 shows the almost complete Powerup_Dollar class (which can
be found in the chapter companion files in Chapter04/AssetsToImport/ ); comments follow.
Listing 4-12. Moving Forward with Powerup_Dollar.cs
01 //-------------------------------------------------------------
02 using UnityEngine;
03 using System.Collections;
04 //--------------------------------------------------------------
05 public class Powerup_Dollar : MonoBehaviour
06 {
07 //Amount of cash to give player
08 public float CashAmount = 100.0f;
09
10 //Audio Clip for this object
11 public AudioClip Clip = null;
12
13 //Audio Source for sound playback
14 private AudioSource SFX = null;
15 //--------------------------------------------------------------
16 void Start()
17 {
18 //Find sound object in scene
19 GameObject SoundsObject = GameObject.FindGameObjectWithTag("sounds");
20
21 //If no sound object, then exit
22 if(SoundsObject == null) return;
23
24 //Get audio source component for sfx
25 SFX = SoundsObject.GetComponent<AudioSource>();
26 }
27 //--------------------------------------------------------------
28 //Event triggered when colliding with player
29 void OnTriggerEnter(Collider Other)
30 {
31 //Is colliding object a player? Cannot collide with enemies
32 if(!Other.CompareTag("player")) return;
33
34 //Play collection sound, if audio source is available
35 if(SFX){SFX.PlayOneShot(Clip, 1.0f);}
36
37 //Hide object from level so it cannot be collected more than once
38 gameObject.SetActive(false);
39
 
Search WWH ::




Custom Search