I have been trying to play a sound after a character jumps and land on ground. This basically means that the sound should be played when the character and the ground collides. The problem is that if i use the function On_Message and add my code after the geometry handling, it would keep playing, because its triggered with each frame on collision.
I was trying to find an event that would be triggered one time only at collision, but couldn’t find anything. In the end i created a boolean variable and manipulated it on jumping input and ground collision. Now my question, is there a proper solution for this or should i use the same methodology for any future problem like this?
To answer I will just assume:
I assume you are using kinematic physics like in a few of the tutorials (instead of dynamic physics)
I assume that you are controlling the movement speed in some vectors that is impacted by collision triggers.
Actually it makes sense that sound is triggered all the time as gravity will force you down and trigger a collision all the time. If you have a speed vector, why not check the previous speed when collision is detected and see if it points down more than a specific gate-value.
If so, play the sound.
(So if player is falling down in a specific speed or higher, play the sound when colliding)
You could also check the penetration DISTANCE (how “far in” the collision went) to decide if sound should be played.
Thanks @andreas.strangequest. It didn’t occur me to use the velocity or distance to achieve my goal. This is probably because i am new to the whole gaming development concept. I used the variable self.last_velocity which stores the last velocity recored from the update event.
The below code solved my issue:
--trigger landing sound
if self.last_velocity.y < 0 then
msg.post("/sound_gate#script", "play_gated_sound", { soundcomponent = "/sound_gate#land", gain = 0.4 })
end