- Home /
Footsteps with iTween MoveTo
In my game the character moves point-to-point, floating through the air, but I would like footstep sounds. Anything collision/animation related won't work.
I'm looking at "rigidbody.velocity" to get the x/y/z velocity, but it's in Update and spams 100 sounds. How can I modify this?
using UnityEngine;
using System.Collections;
public class Footsteps : MonoBehaviour {
public AudioClip audioFootsteps;
void Update()
{
print("PLAYER VELOCITY " + rigidbody.velocity);
if (rigidbody.velocity.x > 0.1 ||
rigidbody.velocity.y > 0.1 ||
rigidbody.velocity.z > 0.1 ||
rigidbody.velocity.x < -0.1 ||
rigidbody.velocity.y < -0.1 ||
rigidbody.velocity.z < -0.1)
{
AudioSource.PlayClipAtPoint(audioFootsteps, transform.position);
}
}
}
Answer by Julien-Lynge · Aug 09, 2011 at 07:01 PM
The code you have will kick of the footstep sound at every frame (i.e. every 0.02 sec or so) as long as the character is moving. What you want is either to look at your character animation each frame and kick off a sound when a foot strikes the ground (complicated but the best solution) or something simpler like kicking off a sound after a certain distance from the last sound.
Code like the following would be a quick solution to get what you're looking for:
using UnityEngine;
using System.Collections;
public class Footsteps : MonoBehaviour {
public AudioClip audioFootsteps;
private Vector3 prevPosition;
float minDistance = 1f;
void Start()
{
prevPosition = transform.position;
}
void Update()
{
if (Vector3.Distance(transform.position, prevPosition) > minDistance)
{
AudioSource.PlayClipAtPoint(audioFootsteps, transform.position);
prevPosition = transform.position;
}
}
}
You might have to massage that, I haven't actually tested it. In a nutshell, mark the player position, check the distance from that position, and when you're far enough away, fire off a sound and set this new position as our previous position. Not very elegant, but it'll work for you.
-Julien
Your answer
Follow this Question
Related Questions
Footstep Script Not Working 2 Answers
Random footsteps 5 Answers
Footstep sounds when walking 7 Answers
What's the easiest way of changing footsteps sound depending on floor material? 3 Answers
Strange Bug or Code Error with footsteps? -1 Answers