Game sound effects help

I am currently making a Labyrinth game. I was wondering how i could make a marble rolling sound only when the marble is rolling. I have it where the board tilts like the real game.


from bge import logic
from mathutils import Vector

cont = logic.getCurrentController()
own = cont.owner

#define sound actuator
sfx = cont.actuators['Sound']

#get angular velocity of the ball
vel = Vector(own.getAngularVelocity()).magnitude

#set volume of sound based on velocity..
#clamp it to a max of 1.0
sfx.volume = min(1.0, (vel*2)/100)

#only play if the ball is rolling
if vel > 0:
    cont.activate(sfx)
else:
    cont.deactivate(sfx)

I used a similar code on my project to change the volume/pitch of the sound of a ship’s engine based on its speed (also works well with walking/running sounds!). You will probably have to play with the numbers which translate velocity into sfx.volume to get it how you like, but this should make it so the ball will roll louder the faster it is rolling.

so would i just connect this with an always sensor to the ball?

Im not good with coding and stuff so I dont know how I would add this into my game lol

I believe you would just connect it with an always sensor

001.blend (1.2 MB)
heres the blend file. The always sensor didn’t work. So I was wondering if you could send a screenshot of the logic brick system

Sorry, I neglected to explain how to actually set up the script.
Paulsanders is almost right; the script just needs to be set up as a controller on the ball object, with an always sensor w/ positive pulse noodled to it. But you also need the sound actuator which the python controller is noodled to.
Here is a screenshot of how I set up the script.



Note I did make a couple changes from the original code I posted, mostly changing the name of the sound actuator (as you already have one called ‘Sound’) and also having it affect the pitch of the sound as well as its volume. Again, you will want to play with the values vel is being divided by(lines 15-16) to get the desired effect.


It still doesn’t seem to work. Am I doing something wrong here?

Script looks good to me (maybe I am missing something obvious), try opening your game console (Window>Toggle System Console) and running the game to see if it says anything specific other than Blender Game Engine Started (Ended).

Only thing I can think of is maybe your actuator name has an extra space or something? (Script looks valid unless your marble doesn’t actually spin or something)