Jump to content

  • Log In with Google      Sign In   
  • Create Account

#ActualHodgman

Posted 30 January 2013 - 11:04 PM

The point of delegates is that the physics and sound systems don't have to know about each other (when contrasting with interfaces, anyway).
The next layer up in the code base, which does know about physics and audio can then glue together those two independent modules.
 
e.g. In this C# code, when the physics body's HitTheGround method is called, the sound effect's Play method is called, even though physics and sound are completely independent of each other.
class Position { };
//physics module
class RigidBody
{
	public delegate void OnTouch(Position pos);

	public void AddOnTouch(OnTouch e)
	{
		m_onTouchEvents.Add(e);
	}

	public void HitTheGround()
	{
		foreach (var e in m_onTouchEvents)
			e(m_position);
	}

	private List<OnTouch> m_onTouchEvents = new List<OnTouch>();
	private Position m_position = new Position();
}
//audio module
class SoundEffect
{
	public void Play(Position where)
	{
		/*...*/
	}
}
//game (can glue the above together)
class RockEntity
{
	public RockEntity()
	{
		m_body.AddOnTouch(m_sound.Play);
	}
	private RigidBody m_body = new RigidBody();
	private SoundEffect m_sound = new SoundEffect();
}
Which language are you using? I can translate that into C or C++ if you like...

#1Hodgman

Posted 30 January 2013 - 10:58 PM

The point of delegates is that the physics and sound systems don't have to know about each other (when contrasting with interfaces, anyway).
The next layer up in the code base, which does know about physics and audio can then glue together those two independent modules.
 
e.g. In this C# code, when the physics body's HitTheGround method is called, the sound effect's Play method is called, even though physics and sound are completely independent of each other.
class Position { };
//physics module
class RigidBody
{
	public delegate void OnTouch(Position pos);

	public void AddOnTouch(OnTouch e)
	{
		m_onTouchEvents.Add(e);
	}

	public void HitTheGround()
	{
		foreach (var e in m_onTouchEvents)
			e(m_position);
	}

	private List<OnTouch> m_onTouchEvents = new List<OnTouch>();
	private Position m_position = new Position();
}
//audio module
class SoundEffect
{
	public void Play(Position where)
	{
		/*...*/
	}
}
//game (can glue the above together)
class RockEntity
{
	public RockEntity()
	{
		m_body.AddOnTouch(m_sound.Play);
	}
	private RigidBody m_body = new RigidBody();
	private SoundEffect m_sound = new SoundEffect();
}

PARTNERS