- Home /
Making an NPC/Object follow a Sound
I'm making a research about the Unity and other engine resources, and I want to know if is it possible to make, for example, an NPC or another object follow a sound. For example, if I throw the stone into an floor, she makes a noise, and If exists a object in an circular range, this object moves to the stone.
Is it possible to make something like that?
For example: The Object (follower) stays at position [0 0 0] (X Y Z) and listen to all "sounds" next to him (by a range), if I throw a stone (who makes a noise) on position [20 0 0], the "follower" moves at the stone position [20 0 0]. But the "follower" only moves if he "listen" this sound, not if the object pass next to his range (not Physics.Raycast, for example).
Sorry if I cannot explain right. :/
Answer by Julien-Lynge · Jan 09, 2012 at 04:46 PM
The easiest way to have objects move towards a sound is to keep the objects that are 'listening' in a catalog and let the catalog know every time a sound is produced. To register your objects, set up a script with something like the following (C#), where MyScript is the (non-static) class that moves the GameObjects towards the sound. Please note that this is psuedo-code and hasn't been tested.
(catalog object)
MyCatalog.cs
List<Transform> listenerTransforms = new List<Transform>();
public void registerListener(MyScript script)
{
listenerTransforms.add(script.transform);
}
public void checkListenersAgainstSound(Vector3 position)
{
foreach(Transform listener in listenerTransforms)
if (Vector3.Distance(position, listener.position < someValue))
listener.GetComponent<MyScript>().moveTowardsSount(Vector3 position);
}
(listener)
MyScript.cs
void Start()
{
FindObjectOfType(typeof(MyCatalog)).registerListener(this);
}
(object producing the sound)
SoundProducer.cs
MyCatalog catalog;
void Start()
{
catalog = FindObjectOfType(typeof(MyCatalog));
}
void produceSound()
{
//start playing the sound
[code]
//let the catalog know to check against this sound
catalog.checkListenersAgainstSound(transform.position)
}
Thanks, I will study this code later (when I get off the work)
I don't want to abuse, but do you have a example like this, but in Javascript? :P
hrm... Offhand, most things should be the same, except change the methods (void produceSound() -> function produceSound() : void) and change the variable declarations ($$anonymous$$yCatalog catalog; -> var catalog : $$anonymous$$yCatalog). I really don't work in JS much, so there may be other things. Take a look at this link: http://fragileearthstudios.com/2011/10/18/unity-converting-between-c-and-javascript-2/