Using box2d cocos2d
, I need to play a hit sound when a b2body
touches another one.
I know how to detect the collision. The problem is that after they collide, they sometimes still touch one another, and I DON'T want to play that sound again (like in real world ,a sound happen if 2 bodies collide at high speed only)
So, I need to play the sound only if they hit in a certain speed/acceleration.
Can i get the body speed when collide?
//some code to meet the standards of the site :
int speed=body->getInertzia;
if(speed>10)
sound!
There are a variety of ways you can do this.
The simplest would be to use the difference in velocity of the objects at the time they hit, using GetLinearVelocity for each body.
You could use GetLinearVelocityFromWorldPoint to compare the velocities at the actual collision location, for a more accurate value.
To take into account the mass of the bodies as well, you could look at the magnitude of the impulses that the physics engine applied to push the bodies apart. This can be done in the PostSolve function of the collision listener. Note that the PostSolve event will occur continuously while the two bodies are in contact, so it is more useful for controlling longer sounds like scraping, rather than the initial impact.
In each of these cases you would probably want to check that the value is above a certain threshold before playing a sound. Bodies can have tiny separations as they slide across each other that you can barely see, but will cause many BeginContact/EndContact events.
In my experience this is a pretty tricky thing to manage. You may also want to check that a sound has not already been played for the contact in the last n milliseconds, to avoid stuttering, especially when using the PostSolve method and a heavy collision occurs which exceeds the threshold value for multiple timesteps.
See this for more details: http://www.iforce2d.net/b2dtut/collision-anatomy