About AI detecting a sound
Hello! I'm trying to make AI detecting a sound. I kinda know how it works. But can't make it on C# Script.
My idea is I use Raycast and if the sound is made, it will caculate the distance between AI and the sound. If the distance is =<10f, the AI will follow the sound.
I'm not use to making script with Raycast and I really need help. Someone Please help me.
Answer by Hellium · Nov 20, 2017 at 03:58 PM
Why don't you use triggers instead? Put a sphere trigger around the sound source. When the sound is emitted, all the ennemies inside the trigger will be notified.
// Set up a list to keep track of targets
public List targets = new List();
// If a new enemy enters the trigger, add it to the list of targets
void OnTriggerEnter(Collider other){
if (other.CompareTag("Enemy")) {
GameObject go = other.gameObject;
if(!targets.Contains(go)){
targets.Add(go);
}
}
}
// When an enemy exits the trigger, remove it from the list
void OnTriggerExit(Collider other){
if (other.CompareTag("Enemy")) {
GameObject go = other.gameObject;
targets.Remove(go);
}
}
public void EmitSound()
{
// Play your sound
// ...
for( int i = 0 ; i < targets.Count ; ++i)
{
targets[i].GetComponent<EnemyScript>().FollowMe( transform ) ;
}
}
Thx. But with this idea, the sound will go through the wall.. I don't want the sound to go through the wall.
Then, simply cas a ray inside the loop when sound is emitted to check whether the ennemy is not behind an obstacle before calling the desired function.
Your answer
Follow this Question
Related Questions
Raycast doesn't stay in one place 0 Answers
Physics Raycast not working 1 Answer
raycasthit to set new move location 0 Answers
Use raycast to change color 1 Answer
Player in front of enemy check not working, Physics.Raycast()? 1 Answer