Contact Listener and Sound.

Howdy!
Im about to finish my first box2d game but i have a serious problem though. Im trying to add some sound when 2 bodies hit eachother.
The problem is that im using my contact listener and override the functions there. The problem is that the contact listener is based on points so whenever 2 points from 2 bodies are hiting eachother the sound play so if more points form those 2 bodies hit the sound will play over and over and im not sure what to do.
I just want the sound to play once when the bodies collide even if more points from those 2 objects get contact.

Here's my contact listener code:

Code: Select all


override public function Add(point:b2ContactPoint):void
      {
         if(point.shape1.IsSensor() || point.shape2.IsSensor())
         {
            soundChannel1.stop();
         }
         if(point.shape1.GetBody().GetMass()==0 || point.shape2.GetBody().GetMass()==0)
         {
            soundChannel1=soundContact1.play();
            soundChannel1.soundTransform=Volume5;
         }
         if(point.shape1.GetBody().GetMass()>0 && point.shape2.GetBody().GetMass()>0)
         {
            soundChannel1=soundContact3.play();
            soundChannel1.soundTransform=Volume5;
         }
         
         
         
      }
      override public function Persist(point:b2ContactPoint):void
      {
         soundChannel1.stop();
         
         
      }
      override public function Remove(point:b2ContactPoint):void
      {
         soundChannel1.stop();
         
         super.Remove(point);
      }
      override public function Result(point:b2ContactResult):void
      {
         
         
      }



Trying to stop the sound if the contact "Persists" but not geting much effect!
So any suggestion how i should do this? I would appreciate.
help!
🙁
This seems more like a general programming question than a Box2D question. x]

Anyway, you'll have to keep track of the collision of both bodies. You can use an array to keep track of collision pairs and a contact count, then check against that array (and the contact count) to see if you need to create a sound.
i have no idea how to do that 🙁
I have managed to solve it with linearVelocity kinda like Force of Impact.
Dont know if its the greatest way but works for now 😀

Code: Select all


if(point.shape1.GetBody().GetLinearVelocity().x>8 || point.shape1.GetBody().GetLinearVelocity().x<-8) // and also on Y axis
{
     playSound
}



This way theres no sound spamming on little impacts.
Heh, that's actually better than my suggestion. I was thinking the sound portion was a key game element, not a simple "bump" sound, so I suggested something a little complicated. Using linear velocity to determine if it should make a sound is actually the right approach. -]

Original thread: https://box2d.org/forum/viewtopic.php?t=8602