I have a problem with the sound, that it only plays once. Afterwards it doesnt repeat. Can someone tell me whats wrong in this script?
var speed = 3.0;
var rotateSpeed = 3.0;
var footStep;
private var moveDirection = Vector3.zero;
function Awake ()
{
footStep = GetComponent(typeof(AudioSource)) as AudioSource;
}
function Update ()
{
var controller: CharacterController = GetComponent(CharacterController);
transform.Rotate(0, Input.GetAxis("Mouse X") * rotateSpeed, 0);
var moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
PlayWalkingSound();
controller.Move(moveDirection * Time.deltaTime);
}
function PlayWalkingSound()
{
footStep.Play();
}
What happens is that it just starts the sound and then stop playing. Before i was checking if the walking keys were pressed, and it worked after the player pressed and released it, but if the player kept the keys pressed it didnt play the footstep sound. Any enlightnements?
you play a sound every update? that doesn’t sound right at all. That means every frame, i.e. several times a second. Your player character a centipede?
You can actually use AudioSource.isPlaying to determine if the AudioSource is currently playing a clip. Just setup an AudioSource specifically for playing this sound, and only play it if it is not already playing (and only if the player is moving, of course).
I just started with Unity a few days ago and my scripting skills aren’t great, but here’s my solution to this problem.
Create a script component that attaches to the player. You can call it “PlayerWalker” or something like that. I’ll write the script psuedocode below.
Create a local variable for the script that initializes with the Transform.position variable. You could call it “last step” or something like that. It basically represents the last place the player took a step.
Then in your Awake() function you can check to see if the difference between the player’s current position and their “last step” position exceeds a certain amount. That amount would be an exposed variable “step distance”.
So I guess it’s something like this:
If the vector distance between player.transform.position and “last step” is greater than “step distance”,
{
play the audio of a step sound
reset the “last step” position to the current player’s position
}
I think that would work.
Of course, if your player is capable of jumping or falling, then you need to add an extra conditional in there so that the step sound is not played while the player is in mid-air.