- Home /
On Collision, Play Sound If Button Is Pressed
Hi
I was looking to have the game play a walking sound while only on a certain object(s), in this case, a wooden pillar. I wanted to write a script where when the player was on this wooden pillar, the sound would play if he moved around, in this case pressing W.
Heres the script I have so far, feel free to let me know if i was way off or not
If you need any additional info, let me know!
var StepSound : AudioClip;
function OnCollisonEnter(collision : Collision)
{
if (other.tag == "pillar")
{
function Update()
{
if (Input.GetKeyDown (KeyCode.W))
{
audio.clip = StepSound;
audio.Play();
}
if (Input.GetKeyUp (KeyCode.W))
{
audio.Stop();
}
}
}
}
I wish to clarify : are you asking for a way to play a specific sound based on what type of floor the character is standing on?
Couple of things I have to point out with your script. OnCollisionEnter only happens once, so you are asking if collision just happened and the player pressed W all in the same frame*. That is asking alot, either some amazing powers of prediction or amazing reflexes !
If you want to check for all the time that the object is within the collider, you need to use OnCOllisionStay : http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionStay.html
I would personally put an arguement in for a raycast. If you programmed it just right, you would only need to raycast in the frame that the footstep sound is played. Which brings me to another point.
Footstep sound i assume is a single sound, I mean that it just goes 'tap' once (not tap-tap-tap). So normally a timer or Invoke function would be used so you could set the ti$$anonymous$$g of the tap-tap-tap so it sounds like a real walking pace. Then you can play with this timer number to change the speed of the tap-tap-tap for running or walking, see =]
There is a script I wrote for that, but it is written for use with the character controller. SO what I suggest is an InvokeRepeating command, that is set to footstepSpeed. then you could just raycast for the type of floor you are standing on, and play the approprate speed and sound all in just a few lines of code. Then you could have a main loop to check if running or walking, and simply CancelInvoke and start InvokeRepeating again with the new time delay.
Answer by cdrandin · Jan 10, 2013 at 10:50 AM
See if this helps http://www.lynda.com/home/Player.aspx?lpk4=109295&playChapter=False @ time 4:40
Hi, that link is for paid subscribers only. Perhaps you could find a free video for everyone to watch, or explain what you were trying to show with that link, thanks.
Your answer
Follow this Question
Related Questions
Player should move box, Ai shouldn't 1 Answer
Audio Script 1 Answer
After collision rotate and move 1 Answer
Play Animation OnTriggerEnter 2 Answers