Sunday, April 26, 2015

Week 4 - Listening for Sound Triggers

During this week the time has come to add functionality to add sounds based on events in the game. To do this, I added a SoundEventListener to our scripts that keep track of character movement. First I declared a delegate:

  public delegate void SoundEventHandler(object sender, CharacterMovement.MoveEventArgs e);


Then declare the event handler and initialize it in Start:

  public event SoundEventHandler SoundEvent;
...
  void Start()
  { 
    SoundFXController soundController = FindObjectOfType();
    if(soundController != null)
    {
      soundController.InitializeSoundEventListener(this);
    }
      
...
  }
And here is what the InitializeSoundEventListener looks like:

        
  public void InitializeSoundEventListener(CharacterMovement cm)
  {
    cm.SoundEvent += new SoundEventHandler(SoundEvent);
  }


In the MoveEventArgs, I can indicate which action is triggering the sound event:

        
  public class MoveEventArgs : EventArgs
  {
    public Movement moveEvent;

    public enum Movement 
    {
      Spin,
      Jump
    };
  }


Then in the SoundFXController I can interpret which action and play the appropriate sound:

        
  private void SoundEvent(object sender, CharacterMovement.MoveEventArgs e)
  {
    switch(e.moveEvent)
    {
    case CharacterMovement.MoveEventArgs.Movement.Spin:
      PlaySpin();
      break;
    case CharacterMovement.MoveEventArgs.Movement.Jump:
      PlayCustomJump();
      break;
    default:
      break;
    }
  }

No comments:

Post a Comment